普通結構
— 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 Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from config.dev_setting import AppConfig
def creat_abb(config):
app = Flask(__name__)
app.config.from_object(config)
return app
app = creat_abb(AppConfig)
cors = CORS(app)
db = SQLAlchemy(app)
@app.route('/')
def hello():
return "hello, home page"
common
libs
models
models.py
# coding: utf-8
from sqlalchemy import BigInteger, Column, Date, Integer, Numeric, String, Table
from application import db
class 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,request
from applog import logger
from flask_sqlalchemy import SQLAlchemy
from common.models import User,db
import random
user = 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.values
logger.debug(req)
login_name = req.get("username")
token = 7788
userinfo = {"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,db
from 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 sys
sys.exit(main())
except Exception as e:
import traceback
traceback.print_exc()
requirement.txt 擴展列表
static 靜態文件夾
templates 模板存放文件夾
router.py 路由
from application import app
from controllers.blueprints import user
app.register_blueprint(user,url_prefix='/user')
這裏還整了一個日志記錄
import logging
# create logger
logger = logging.getLogger('controllers.blueprints.py')
logger.setLevel(logging.DEBUG)
# create file handler and set level to debug
handler = logging.FileHandler('log.txt', 'a')
handler.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to handler
handler.setFormatter(formatter)
# add handler to logger
logger.addHandler(handler)
更好的結構
自定义启动命令
需要pip install flask_script
使用這個工具,可以使用自定義命令來啓動項目。
但是這個作者說,flask官方的Command Line Interface更好用。官方的cli是依賴click庫的。
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command("create-user")
@click.argument("name")
def create_user(name):
...
多环境配置文件
Debug工具flask_debugtoolbar
正常安装后,是右侧这个样子的,但是不知道为什么一开始并没有成功。