Flask应用指南


一、入门程序

#encoding: utf-8
from flask import Flask,render_template
app = Flask(__name__)

# 首页
@app.route('/')
def page1():
    return render_template('page1.html')

if __name__ == '__main__':
    app.run(debug=True,port=5000,host='0.0.0.0')

二、环境配置

依赖安装

  1. pip3 install flask
  2. pip3 install sqlalchemy
  3. pip3 install mysql-connector

开发模式

  1. python app.pyflask 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

四、部署上线

五、总结

  1. Flask部署方式主要有uWSGIGunicorn,推荐使用后者