Python中Flask框架專案拆分
阿新 • • 發佈:2018-11-23
新建flask專案,建Python package包,把static、template拉進去,
新建 settings.py、models.py、init.py、ext.py、views.py,
在預設建立的app.py導包,
from flask_script import Manager from flask_migrate import MigrateCommand from myapp import create_app app = create_app('debug') manage = Manager(app) manage.add_command('db',MigrateCommand) if __name__ == '__main__': manage.run()
settings.py中配置:各種配置
from redis import StrictRedis from os import environ def get_db_uri(conf): uri = "{backend}+{engine}://{user}:{pwd}@{ip}:{port}/{db}".format( backend=conf.get("backend"), engine=conf.get("engine"), user=conf.get("user"), pwd=conf.get("pwd"), ip=conf.get("host"), port=conf.get("port"), db=conf.get("db") ) return uri class Config: # 公共的配置 Debug = False Test = False Online = False SECRET_KEY = "djhsdfjkashkwn" SESSION_TYPE = "redis" SESSION_KEY_PREFIX = "myapp:" SQLALCHEMY_TRACK_MODIFICATIONS = False class DebugConofig(Config): Debug = True SESSION_REDIS = StrictRedis(host="127.0.0.1", db=5) # 資料庫配置 DATABASE = { "engine": "pymysql", "backend": "mysql", 'user': environ.get("DBUSER"), 'pwd': environ.get("DBPWD"), "host": "127.0.0.1", "port": 3306, "db": '資料庫' } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) class TestConfig(Config): Test = True SESSION_REDIS = StrictRedis(host="127.0.0.1", db=6) # 資料庫配置 DATABASE = { "engine": "pymysql", "backend": "mysql", 'user': environ.get("DBUSER"), 'pwd': environ.get("DBPWD"), "host": "127.0.0.1", "port": 3306, "db": '資料庫' } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) class OnlineConfig(Config): Online = True SESSION_REDIS = StrictRedis(host="127.0.0.1", db=7) # 資料庫配置 DATABASE = { "engine": "pymysql", "backend": "mysql", 'user': environ.get("DBUSER"), 'pwd': environ.get("DBPWD"), "host": "127.0.0.1", "port": 3306, "db": '資料庫' } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) conf = { "debug": DebugConofig, "test": TestConfig, "online": OnlineConfig }
models.py 跟django下models一樣
from myapp.ext import db
先匯入db
__init__.py 建立app,匯入配置,註冊藍圖,註冊第三方外掛
from flask import Flask from myapp import settings from myapp.ext import init_ext from myapp.views import init_blue def create_app(env_name): # 例項化app app = Flask(__name__) # 配置 app.config.from_object(settings.conf.get(env_name,'debug')) # 例項化第三方 init_ext(app) # 藍圖 init_blue(app) return app
ext.py 第三方外掛
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_migrate import Migrate
db = SQLAlchemy()
def init_ext(app):
db.init_app(app)
se = Session()
se.init_app(app)
migrate = Migrate(app=app, db=db)
建立藍圖,並註冊