Flask拆分/结藕
项目结构
- manage.py 项目管理文件
- App 目录
- __init__.py 初始化文件
- settings.py 全局配置文件
- extends.py 扩展库,用户扩展项目插件
- views.py 路由,视图函数
- models.py 定制模型
manage.py
import os from flask_script import Manager from flask_migrate import MigrateCommand from App import create_app # 环境变量,获取当前Flask环境 env = os.environ.setdefault('FLASK_ENV','devlop') # 生成app app = create_app(env) manager = Manager(app) # 给manage.py 添加数据库迁移的命令 manager.add_command('db',MigrateCommand) if __name__ == '__main__': manager.run()
App/__init__.py
from flask import Flask # 初始化app,并返回 from App.settings import envs from App.extends import init_extends from App.views import init_views def create_app(env): # 创建Flask的app对象 app = Flask(__name__) # 加载配置文件 app.config.from_object(envs.get(env)) # 初始化扩展对象 init_extends(app) # 初始化视图 init_views(app) return app
App/settings.py
import re class Config(object): DEBUG = False TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False @classmethod def get_db_uri(cls,dbinfo): engine = dbinfo.get('ENGINE') or "sqlite3" driver = dbinfo.get('DRIVER') or "" name = dbinfo.get('NAME') or "" user = dbinfo.get('USER') or "" port = dbinfo.get('PORT') or "" host = dbinfo.get('HOST') or "" password = dbinfo.get('PASSWORD') or "" if re.match(r'^sqlite3?$', engine): # 默认是sqlite数据库 db_uri = "{}://{}/{}.{}".format(driver, host, name, engine) else: # database: engine+driver://user:password@host:port/database db_uri = "{}+{}://{}:{}@{}:{}/{}".format( engine, driver, user, password, host, port, name) # 返回数据库连接地址 return db_uri class DevlopConfig(Config): DEBUG = True # dbinfo = { # # } # 加载数据库 # SQLALCHEMY_DATABASE_URI = super().get_db_uri(dbinfo) SQLALCHEMY_DATABASE_URI = 'sqlite:///demo3.sqlite3' # 设置环境设置配置 envs = { 'devlop':DevlopConfig, } def config(): """当前的配置文件""" return envs.get(os.environ.get('FLASK_ENV'))
App/views.py
from flask import Blueprint blue = Blueprint('blue',__name__) def init_views(app): app.register_blueprint(blue) @blue.route('/') def index(): return "Index"
App/extends.py
from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy models = SQLAlchemy() migrate = Migrate() def init_extends(app): # 初始化模型类,及迁移模型对象 models.init_app(app) migrate.init_app(app,models)
App/models.py
from .extends import models class User(models): id = models.Column(models.Integer,primary_key=True) username = models.Column(models.String) password = models.Column(models.String)
转载请标明出处:http://www.cnblogs.com/duzhaoqi/