1. 创建文件夹(或从pycharm直接创建)
在桌面随意创建一个空文件夹
2.下载所需插件
下载命令 pip install -r txt文件名
3.创建启动文件
创建app.py文件,用工厂方法的方式将app封装起来,再创建一个create_app.py文件
create_app
from flask import Flask
from models.models import db
from views.user_bp import user_bp
from flask_cors import CORS
def create_app(config):
flask_app = Flask(__name__)
CORS(flask_app)
flask_app.config.from_object(config)
db.init_app(flask_app)
flask_app.register_blueprint(user_bp)
return flask_app
加载配置项 要再创建settings目录创建config
非载入七牛云容联云版本
class DefaultConfig:
SECRET_KEY = "asdaweq"
SQLALCHEMY_DATABASE_URI=""
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_ECHO=True
JSON_AS_ASCII=False
SMS_TIME = 5
class DevConfig(DefaultConfig):
SQLALCHEMY_DATABASE_URI="mysql+pymysql://root:123@127.0.0.1:3306/h2111p7"
载入容联云七牛云版本
settings文件里配置secret.py文件配置容联 七牛
class SecretConfig():
RL_ACC_ID = ""
RL_ACC_TOKEN = ""
RL_APP_ID = ""
RL_TID = "1"
REDIS_HOST = "127.0.0.1"
REDIS_PORT =6379
QINIU_AK = ''
QINIU_SK = ''
QINIU_BUCKET_NAME = ''
QINIU_BASE_URL = ''
在settings目录创建config
from settings.secret import SecretConfig
class DefaultConfig(SecretConfig):
SECRET_KEY = "asdaweq"
SQLALCHEMY_DATABASE_URI=""
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_ECHO=True
JSON_AS_ASCII=False
SMS_TIME = 5
class DevConfig(DefaultConfig):
SQLALCHEMY_DATABASE_URI="mysql+pymysql://root:123@127.0.0.1:3306/h2111p7"
app
from create_app import create_app
from settings.config import DevConfig
app = create_app(DevConfig)
if __name__ == '__main__':
app.run()
4.创建蓝图
创建views视图下的py文件
from flask import Blueprint,Resource
user_bp = Blueprint("user_bp",__name__,url_prefix="/users")
api = Api(user_bp)
class UserView(Resource):
def get(self):
pass
api.add_resource(类名,"/路由名")
5.创建模型类
创建一个model目录下的models.py文件
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
class UserModel(db.Model):
uid = db.Column(db.Integer,primary_key=True,autoincrement=True,comment="用户ID")
mobile = db.Column(db.String(11),comment="手机号")
username = db.Column(db.String(32),default="",comment="昵称")
img = db.Column(db.String(200),default="",comment="头像")
reg_time = db.Column(db.DateTime,default=datetime.now,comment="注册时间")
intro = db.Column(db.String(256),default="这个人很懒,什么都没有留下",comment="简介")
status = db.Column(db.Boolean,default=False,comment="true:冻结 false:正常")
根目录创建manage.py文件
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from app import app
from models.models import db
manage = Manager(app)
migrate = Migrate(app,db)
manage.add_command("db",MigrateCommand)
if __name__ == '__main__':
manage.run()
6.JWT 七牛云 容联云的配置
创建utils文件
JwtTool 配置
import time
import jwt
from flask import current_app
class JwtTool():
'''
jwt管理
'''
def create(self,payload,ex=3600):
'''
生成jwt
:param payload: 载荷
:return: string jwt
'''
payload["exp"] = int(time.time())+ ex
secret_key = current_app.config.get("SECRET_KEY")
token = jwt.encode(payload,secret_key,algorithm="HS256")
return token
def valid(self,token):
'''
校验jwt
:param token: JWT
:return: 返回payload
'''
secret_key = current_app.config.get("SECRET_KEY")
try:
payload = jwt.decode(token, secret_key, algorithms="HS256")
return payload
except Exception as e:
print(e)
return False
if __name__ == '__main__':
from app import app
with app.app_context():
j = JwtTool()
jwt_token = j.create({
"aaa":"bbb"
})
a = j.valid(jwt_token)
print(a)
QiniuTool文件的配置 七牛云上传文件
from qiniu import Auth,put_file
from flask import current_app
class QiniuTool():
def __init__(self):
ak = current_app.config.get("QINIU_AK")
sk = current_app.config.get("QINIU_SK")
self.q = Auth(ak,sk)
self.bucket_name = current_app.config.get("QINIU_BUCKET_NAME")
def upload(self,localfilepath,newfilename):
'''
七牛云上传图片
:param localfilepath: 本地文件地址
:param newfilename: 上传后的文件名
:return:
'''
token = self.q.upload_token(self.bucket_name,newfilename,expires=3600)
print(token)
res = put_file(token,newfilename,localfilepath,version='v2')
print(res)
if res[0]['key'] == newfilename:
return newfilename
else:
return False
if __name__ == '__main__':
from app import app
with app.app_context():
QiniuTool().upload("./../static/img/图片.png",'static/img/图片.png')
SmsTools的配置 容联云发送短信
from ronglian_sms_sdk import SmsSDK
from flask import current_app
import json,redis
class SmsTool():
'''
发送短信类
'''
def __init__(self):
accId = current_app.config.get("RL_ACC_ID")
accToken = current_app.config.get("RL_ACC_TOKEN")
appId = current_app.config.get("RL_APP_ID")
self.sdk = SmsSDK(accId,accToken,appId)
host = current_app.config.get("REDIS_HOST")
port = current_app.config.get("REDIS_PORT")
self.rds = redis.Redis(host=host,port=port)
def send(self,phone,code):
'''
发送短信接口
:param phone: 手机号
:param code: 验证码
:return: Bool 发送成功开始失败
'''
tid = current_app.config.get("RL_TID")
t = current_app.config.get("SMS_TIME")
key = "sms_%s"%phone
self.rds.set(key,code,ex=t*60)
datas = (code,t)
rs = self.sdk.sendMessage(tid,phone,datas)
rs_data = json.loads(rs)
if rs_data["statusCode"] == "000000":
return True
return False
|