普通結構
— application.py 全局變量
— common
— libs
— models
— config 配置文件
—controllers
— index.py
— manger.py 文件入口
—requirement.txt 擴展列表
— static 靜態文件夾
— templates 模板存放文件夾
— common
— index.html
— www.py 路由
application.py 全局變量
from flask import Flaskfrom flask_cors import CORSfrom flask_sqlalchemy import SQLAlchemyfrom config.dev_setting import AppConfigdef creat_abb(config):app = Flask(__name__)app.config.from_object(config)return appapp = creat_abb(AppConfig)cors = CORS(app)db = SQLAlchemy(app)@app.route('/')def hello():return "hello, home page"
common
libs
models
models.py
# coding: utf-8from sqlalchemy import BigInteger, Column, Date, Integer, Numeric, String, Tablefrom application import dbclass User(db.Model):__tablename__ = 'user'id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(255))password = db.Column(db.String(255))
config 配置文件
dev_setting.py
class AppConfig():SQLALCHEMY_DATABASE_URI='mysql+pymysql://juha:123@10.202.0.201/tranfer_data'SQLALCHEMY_TRACK_MODIFICATIONS = True
controllers
blueprints.py
from flask import Blueprint,make_response,jsonify,requestfrom applog import loggerfrom flask_sqlalchemy import SQLAlchemyfrom common.models import User,dbimport randomuser = Blueprint("user",__name__)@user.route('/login',methods=['POST'])def index():logger.debug(db.session.query(User.name,User.password).all())logger.debug(request)req = request.valueslogger.debug(req)login_name = req.get("username")token = 7788userinfo = {"name":"tom","age":25,"token":token}response = make_response(jsonify(userinfo))return response@user.route('/logout',methods=['POST'])def hello():return "logout page"
manger.py 文件入口
將自定義的命令寫道這個文件中
from application import app,dbfrom router import *import click##web server 使用flask runserver即可啓動@app.cli.command("runserver")def runserver():app.run(host="0.0.0.0",port=7755,debug=True)def main():runserver()if __name__ == '__main__':try:import syssys.exit(main())except Exception as e:import tracebacktraceback.print_exc()
requirement.txt 擴展列表
static 靜態文件夾
templates 模板存放文件夾
router.py 路由
from application import appfrom controllers.blueprints import userapp.register_blueprint(user,url_prefix='/user')
這裏還整了一個日志記錄
import logging# create loggerlogger = logging.getLogger('controllers.blueprints.py')logger.setLevel(logging.DEBUG)# create file handler and set level to debughandler = logging.FileHandler('log.txt', 'a')handler.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to handlerhandler.setFormatter(formatter)# add handler to loggerlogger.addHandler(handler)
更好的結構
自定义启动命令
需要pip install flask_script
使用這個工具,可以使用自定義命令來啓動項目。
但是這個作者說,flask官方的Command Line Interface更好用。官方的cli是依賴click庫的。
import clickfrom flask import Flaskapp = Flask(__name__)@app.cli.command("create-user")@click.argument("name")def create_user(name):...
多环境配置文件
Debug工具flask_debugtoolbar
正常安装后,是右侧这个样子的,但是不知道为什么一开始并没有成功。
