普通結構

— application.py 全局變量
— common
— libs
— models
— config 配置文件
—controllers
— index.py
— manger.py 文件入口
—requirement.txt 擴展列表
— static 靜態文件夾
— templates 模板存放文件夾
— common
— index.html
— www.py 路由

application.py 全局變量

  1. from flask import Flask
  2. from flask_cors import CORS
  3. from flask_sqlalchemy import SQLAlchemy
  4. from config.dev_setting import AppConfig
  5. def creat_abb(config):
  6. app = Flask(__name__)
  7. app.config.from_object(config)
  8. return app
  9. app = creat_abb(AppConfig)
  10. cors = CORS(app)
  11. db = SQLAlchemy(app)
  12. @app.route('/')
  13. def hello():
  14. return "hello, home page"

common

libs

models

models.py

  1. # coding: utf-8
  2. from sqlalchemy import BigInteger, Column, Date, Integer, Numeric, String, Table
  3. from application import db
  4. class User(db.Model):
  5. __tablename__ = 'user'
  6. id = db.Column(db.Integer, primary_key=True)
  7. name = db.Column(db.String(255))
  8. password = db.Column(db.String(255))

config 配置文件

dev_setting.py

  1. class AppConfig():
  2. SQLALCHEMY_DATABASE_URI='mysql+pymysql://juha:123@10.202.0.201/tranfer_data'
  3. SQLALCHEMY_TRACK_MODIFICATIONS = True

controllers

blueprints.py

  1. from flask import Blueprint,make_response,jsonify,request
  2. from applog import logger
  3. from flask_sqlalchemy import SQLAlchemy
  4. from common.models import User,db
  5. import random
  6. user = Blueprint("user",__name__)
  7. @user.route('/login',methods=['POST'])
  8. def index():
  9. logger.debug(db.session.query(User.name,User.password).all())
  10. logger.debug(request)
  11. req = request.values
  12. logger.debug(req)
  13. login_name = req.get("username")
  14. token = 7788
  15. userinfo = {"name":"tom","age":25,"token":token}
  16. response = make_response(jsonify(userinfo))
  17. return response
  18. @user.route('/logout',methods=['POST'])
  19. def hello():
  20. return "logout page"

manger.py 文件入口

將自定義的命令寫道這個文件中

  1. from application import app,db
  2. from router import *
  3. import click
  4. ##web server 使用flask runserver即可啓動
  5. @app.cli.command("runserver")
  6. def runserver():
  7. app.run(host="0.0.0.0",port=7755,debug=True)
  8. def main():
  9. runserver()
  10. if __name__ == '__main__':
  11. try:
  12. import sys
  13. sys.exit(main())
  14. except Exception as e:
  15. import traceback
  16. traceback.print_exc()

requirement.txt 擴展列表

static 靜態文件夾

templates 模板存放文件夾

— common
— index.html

router.py 路由

  1. from application import app
  2. from controllers.blueprints import user
  3. app.register_blueprint(user,url_prefix='/user')

這裏還整了一個日志記錄

  1. import logging
  2. # create logger
  3. logger = logging.getLogger('controllers.blueprints.py')
  4. logger.setLevel(logging.DEBUG)
  5. # create file handler and set level to debug
  6. handler = logging.FileHandler('log.txt', 'a')
  7. handler.setLevel(logging.DEBUG)
  8. # create formatter
  9. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  10. # add formatter to handler
  11. handler.setFormatter(formatter)
  12. # add handler to logger
  13. logger.addHandler(handler)

更好的結構

自定义启动命令

需要pip install flask_script

使用這個工具,可以使用自定義命令來啓動項目。
但是這個作者說,flask官方的Command Line Interface更好用。官方的cli是依賴click庫的。

  1. import click
  2. from flask import Flask
  3. app = Flask(__name__)
  4. @app.cli.command("create-user")
  5. @click.argument("name")
  6. def create_user(name):
  7. ...

多环境配置文件

Debug工具flask_debugtoolbar

正常安装后,是右侧这个样子的,但是不知道为什么一开始并没有成功。
image.png

请求拦截器

错误处理器