自定义flask启动与多模式使用(7)

目录如下:

自定义flask启动与多模式使用(7)_第1张图片

 

 

安装自动启动模块

pip install flask_script

在manager中配置:

# -*- coding: utf-8 -*-
from application import app,db,manager
from flask_script import Server,Command
from www import *

manager.add_command("runserver",Server(host = "127.0.0.1",use_debugger=True,use_reloader=True))

@Command
def create_all():
    from application import db
    from common.models.user import User
    db.create_all()
manager.add_command("create_all",create_all)

def main():
    manager.run()
if __name__ == "__main__":
    # app.run(  )
    try:
        import sys
        sys.exit(main())
    except Exception as e:
        import traceback
        traceback.print_exc()

application

# -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
import os
app = Flask( __name__ )

manager = Manager(app)
app.config.from_pyfile("config/base_setting.py")
# set ops_config=local,在次项目的根目录终端输入,否则找不到数据库
if "ops_config" in os.environ:
    app.config.from_pyfile("config/%s_setting.py"%(os.environ['ops_config']))
# print(os.environ)
db = SQLAlchemy( app )

多环境配置文件:

# -*- coding: utf-8 -*-
#公用配置
DEBUG = True
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ENCODING = "utf8mb4"
SECRET_KEY = "123456imooc"

# -*- coding: utf-8 -*-
#生产环境配置文件
from config.base_setting import *
DEBUG = False

# -*- coding: utf-8 -*-
#本地开发环境配置文件
from config.base_setting import *
# SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]/mysql"

SECRET_KEY = "imooc123456"

注册调试工具&拦截器

# -*- coding: utf-8 -*-
from application import app
from controllers.index import index_page
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
'''
拦截器的使用
'''
from interceptors.Auth import *
from interceptors.errorHandler import *
app.register_blueprint( index_page,url_prefix = "/" )

拦截器与错误页面处理:

# -*- coding: utf-8 -*-
from application import app

@app.errorhandler( 404 )
def error_404( e ):
    return "404 not found"


# -*- coding: utf-8 -*-
from application import app

@app.before_request
def before_request():
    app.logger.info( "--------before_request--------" )
    return

@app.after_request
def after_request( response ):
    app.logger.info("--------after_request--------")
    return response

 

你可能感兴趣的:(自定义flask启动与多模式使用(7))