Flask应用指南
发表于 · 归类于
技术 · 阅读完需 8 分钟 ·
阅读量 报告错误
一、入门程序
#encoding: utf-8
from flask import Flask,render_template
app = Flask(__name__)
# 首页
@app.route('/')
def page1():
# 注意这里使用了 render_template 函数,
# 它会从 templates 文件夹中寻找对应的 HTML 文件
return render_template('page1.html')
if __name__ == '__main__':
app.run(debug=True,port=5000,host='0.0.0.0')
二、环境配置
依赖安装
pip3 install flask
pip3 install sqlalchemy
pip3 install mysql-connector
开发模式
python app.py
或flask run
三、代码入门
(1)返回json接口
return jsonify(array)
(2)自定义响应头
@app.route('/json')
def sysinfo():
alist = {}
alist['name'] = 'xxx'
resp = make_response(jsonify(alist))
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
(3)接收参数,get获取url
@app.route('/user/<username>')
def user(username):
a = request.args.get('a')
b = request.args.get('b')
return str(a)+','+str(b)+','+username
(4)MySQL查询
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, select,Date
DB_URL = "mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8".format(USERNAME,PASSWORD,HOST,PORT,DATABASE)
engine = create_engine(DB_URL)
DBSession = sessionmaker(bind=engine)
session = DBSession()
alist = session.execute('SELECT * FROM b_admin WHERE `state` = 1')
admins = [];
for h in alist:
admin = {}
admin['account'] = h.account
admin['realname'] = h.realname
admin['role'] = h.role
admins.append(admin)
return admins
(5)异步任务 20220920
from concurrent.futures import ThreadPoolExecutor
import time
executor = ThreadPoolExecutor()
# 模拟耗时任务
def run_job(name):
time.sleep(5)
print('run_job complete', name,flush=True)
@app.route("/run")
def run_async():
name = "this is a async"
executor.submit(run_job, name=name)
print("return now.",flush=True)
return {'ret': 'ok'}
(6)404页面设置
# 自定义 404 错误页面
@app.errorhandler(404)
def page_not_found(e):
# 注意这里使用了 render_template 函数,
# 它会从 templates 文件夹中寻找对应的 HTML 文件
return render_template('404.html'), 404
(6)socket.io写websocket
(7)定时任务-心跳程序
四、部署上线
gunicorn方式部署:
- 安装gunicorn
pip3 install gunicorn
- 运行gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 -D app:app
启动与关闭
- 关闭进程:
killall gunicorn
- 启动进程:
gunicorn -w 4 -b 0.0.0.0:8000 -D app:app
supervisor守护进程
- 安装 yum install supervisor -y
- 配置 /etc/supervisor.d/gunicorn.conf
- 启动 supervisor -c /etc/supervisor.conf
- 重启 supervisorctl restart gunicorn
- 重新加载配置 supervisorctl reload
gunicorn.conf配置文件
[program:gunicorn]
directory=/home/flaskapp
command=gunicorn -w 4 -b :5000 --log-level=warning flaskweb:app
user=root
autostart=true
autorestart=true
loglevel=info
stdout_logfile=/var/log/gunicorn-stdout.log
stderr_logfile=/var/log/gunicorn-stderr.log
使用阿里云函数计算(ServerLess)部署
创建应用>Web框架>Flask
五、总结
- Flask部署方式主要有
uWSGI
和Gunicorn
,推荐使用后者