当前位置:网站首页>Creating seven NiuYun Flask project complete and let cloud
Creating seven NiuYun Flask project complete and let cloud
2022-08-02 14:21:00 【czy1206527605】
1. 创建文件夹(或从pycharm直接创建)
In the desktop randomly create an empty folder
2.下载所需插件
下载命令 pip install -r txt文件名
3.创建启动文件
创建app.py文件,Use the factory method toapp封装起来,再创建一个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)
# 初始化数据库 Of configuration items must be
db.init_app(flask_app)
# Mount the blueprint
flask_app.register_blueprint(user_bp)
return flask_app
加载配置项
To createsettings目录创建config
The load seven NiuYun let al cloud version
# 默认配置项
class DefaultConfig:
SECRET_KEY = "asdaweq"
SQLALCHEMY_DATABASE_URI=""
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_ECHO=True
JSON_AS_ASCII=False
# Verification code configuration items
SMS_TIME = 5
# 开发阶段配置项(Based from the above class)
class DevConfig(DefaultConfig):
SQLALCHEMY_DATABASE_URI="mysql+pymysql://root:[email protected]:3306/h2111p7"
Load capacity of al cloud seven NiuYun version
settings文件里配置secret.pyFile configuration, let al 七牛
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
# 继承自secret中的类
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:[email protected]:3306/h2111p7"
app
# 导入封装的create app
from create_app import create_app
# 导入setting里的配置项
from settings.config import DevConfig
app = create_app(DevConfig)
if __name__ == '__main__':
app.run()
4.创建蓝图
创建views视图下的py文件
from flask import Blueprint,Resource
# 实例化蓝图对象
# url_prefixGlobal routing address
user_bp = Blueprint("user_bp",__name__,url_prefix="/users")
# api 路由收集器
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
# 1.Create a black window
manage = Manager(app)
# 2.Instantiation migration class
migrate = Migrate(app,db)
# 3.Add commands to the black window
manage.add_command("db",MigrateCommand)
if __name__ == '__main__':
manage.run()
6.JWT 七牛云 Let al cloud configuration
创建utils文件
JwtTool 配置
import time
import jwt # pip install pyjwt
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 # 默认有效期1小时
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文件的配置 Seven NiuYun upload files
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的配置 Let al cloud send SMS
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 Send success began to failure '''
tid = current_app.config.get("RL_TID")
t = current_app.config.get("SMS_TIME") # 有效期,从配置文件获取
# 把验证码存入redis里面
key = "sms_%s"%phone
self.rds.set(key,code,ex=t*60)
datas = (code,t)
rs = self.sdk.sendMessage(tid,phone,datas) # 返回的是json字符串
rs_data = json.loads(rs)
if rs_data["statusCode"] == "000000":
return True
return False
# if __name__ == '__main__':
# from app import app
# with app.app_context():
# s = SmsTool()
# s.send("150369602231","6666")
边栏推荐
猜你喜欢
第五单元 保持状态
Mysql's case the when you how to use
海明校验码纠错设计原理
logback源码阅读(二)日志打印,自定义appender,encoder,pattern,converter
paddleocr window10初体验
[ROS] The difference between roscd and cd
Sentinel源码(四)(滑动窗口流量统计)
【Tensorflow】AttributeError: '_TfDeviceCaptureOp' object has no attribute '_set_device_from_string'
WeChat Mini Program-Recent Dynamic Scrolling Implementation
The world's largest Apache open source foundation is how it works?
随机推荐
ZABBIX配置邮件报警和微信报警
Sentinel源码(二)入口方法分析
浅浅写一下PPOCRLabel的使用及体验
[ROS] (01) Create ROS workspace
Go语言初始
Minio文件上传
STM32(F407)—— 堆栈
史上最全!47个“数字化转型”常见术语合集,看完秒懂~
Flask框架
第十一单元 序列化器
使用云GPU+pycharm训练模型实现后台跑程序、自动保存训练结果、服务器自动关机
[ROS] The difference between roscd and cd
vim复制粘贴_vim如何复制粘贴
8581 Linear linked list inversion
What's wrong with running yolov5 (1) p, r, map are all 0
动手学ocr(一)
The bad policy has no long-term impact on the market, and the bull market will continue 2021-05-19
MarkDown语法汇总
window10 lower semi-automatic labeling
[ROS] (05) ROS Communication - Node, Nodes & Master