基础环境
python 3.8.3
Flask 1.1.2
官方文档
英文文档:Flask英文文档
中文文档:Flask中文文档
注:本系列文章主要记录Flask-RESTful
实现一个最简单的Flask服务
Hello.py
文件 将下面内容放进去# 1. 引入Flask
from flask import Flask
# 2. 创建Flask对象
app = Flask(__name__)
# 3. 设置路由
@app.route('/')
def index():
return 'Hello Flask'
# 4. 运行Flask
app.run()
python Hello.py
http://127.0.0.1:5000/
即可看见 Hello Flask文档:https://flask-script.readthedocs.io/en/latest/
模拟 Django
框架 进行拆分
需要使用Flask-Script 进行模拟 Django manage.py 扩展命令行参数
pip install flask-script
from flask import Flask
from flask_script import Manager
# 1. 引入Flask-Script
app = Flask(__name__)
# 2. 使用app构建Manager对象
manager = Manager(app=app)
@app.route('/')
def index():
return 'Hello Flask'
if __name__ == '__main__':
manager.run()
python manage.py runserver
python manage.py runserver --help
-?, --help show this help message and exit
# 指定ip 如:0.0.0.0
-h HOST, --host HOST
# 指定端口 如:5000
-p PORT, --port PORT
# 指定多进程
--threaded
# 指定多进程数量
--processes PROCESSES
# 传递错误
--passthrough-errors
# 开启调试模式
-d, --debug enable the Werkzeug debugger (DO NOT use in production code)
# 关闭调试模式
-D, --no-debug disable the Werkzeug debugger
# 开启自动重启
-r, --reload monitor Python files for changes (not 100% safe for production use)
# 关闭自动重启
-R, --no-reload do not monitor Python files for changes
# 指定SSL证书
--ssl-crt SSL_CRT Path to ssl certificate
--ssl-key SSL_KEY Path to ssl key
文档:https://flask.palletsprojects.com/en/1.0.x/tutorial/blog/
文档:https://flask.palletsprojects.com/en/1.0.x/tutorial/views/
| - App # 整个项目的包目录
| - models # 数据模型
| - static # 静态文件
| - templates # 模板文件
| - index.html # 首页html
| - views # 视图文件
| - __init__.py # 初始化
| - blue_view.py # 蓝图视图文件
| - __init__.py # 项目初始化
| - ext.py # 初始化第三方工具
| - settings.py # 配置文件
| - manage.py # 启动程序
from App import create_app
from flask_script import Manager
app = create_app()
manager = Manager(app=app)
if __name__ == '__main__':
manager.run()
from flask import Flask
from App.views import init_blue
def create_app():
app = Flask(__name__)
# 初始化路由
init_blue(app)
return app
from App.views.blue_view import blue
def init_blue(app):
app.register_blueprint(blue)
from flask import Blueprint, render_template
blue = Blueprint('blue', __name__)
@blue.route("/")
def index():
return render_template('index.html')
文档:https://flask.palletsprojects.com/en/1.0.x/patterns/sqlalchemy/
def get_db_uri(dbinfo):
enqine = dbinfo.get("ENGINE") or "mysql"
driver = dbinfo.get("DRIVER") or "pymysql"
user = dbinfo.get("USER") or "root"
password = dbinfo.get("PASSWORD") or "1234567"
host = dbinfo.get("HOST") or "localhost"
port = dbinfo.get("PORT") or 3306
name = dbinfo.get("NAME") or "Flask"
return "{}+{}://{}:{}@{}:{}/{}".format(
enqine, driver, user, password, host, port, name
)
class Config:
TESTING = False
DEBUG = False
# SQLAlchemy 默认配置
SQLALCHEMY_TRACK_MODIFICATIONS = False
# 加密密钥 越复杂越好
SECRET_KEY = "elephantnote.com"
class DefaultConfig(Config):
"""
默认环境
"""
DEBUG = True
dbinfo = {
"ENGINE": "mysql", # 使用数据库
"DRIVER": "pymysql", # 数据库驱动器
"USER": "root", # 用户
"PASSWORD": "1234567", # 密码
"HOST": "localhost", # 连接地址
"PORT": 3306, # 端口
"NAME": "flask_test" # 数据库名称
}
SQLALCHEMY_DATABASE_URI = get_db_uri(dbinfo)
envs = {
'default': DefaultConfig
}
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy() # 操作数据库
def init_ext(app):
db.init_app(app) # 使用app初始化SQLAlchemy
# 初始化第三方应用
init_ext(app)
from App.ext import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(16))
from App.models.blue_model import User
@blue.route("/get/user/")
def get_user():
user = User.query.all()
return render_template('user.html', user=user)
文档:https://flask-migrate.readthedocs.io/en/latest/
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy() # 操作数据库
migrate = Migrate() # 数据库迁移
def init_ext(app):
db.init_app(app) # 使用app初始化SQLAlchemy
migrate.init_app(app, db) # 使用app初始化Migrate
from flask_script import Manager
manager.add_command('db', MigrateCommand)
python manage.py db init
初始化后项目中会增加migrations
python manage.py db migrate
python manage.py db upgrade