1.2 app工厂以及db问题的解决

app工厂用于模式的选择可以写在配置类文件中,最后配置类文件所有代码如下

 1 from redis import StrictRedis
 2 import logging
 3 class Config(object):
 4 配置类
 5     DEBUG = True
 6     SQLALCHEMY_DATABASE_URI = "mysql://root:hushuai@127.0.0.1:3306/demo"
 7     SQLALCHEMY_TRACK_MODIFICATIONS = False
 8     REDIS_HOST = "127.0.0.1"
 9     REDIS_PORT = 6379
10     SECRET_KEY = "ISADqionsdoiAsid"
11     SESSION_TYPE = "redis"
12     SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
13     SESSION_USE_SIGNER = True
14     SESSION_PERMANENT = 60*60*24
15 
16 #开发工厂
17 class DevelopmentConfig(Config):
18     LEVEL_LOG = logging.DEBUG
19 
20 #生产工厂
21 class ProductionConfig(Config):
22     DEBUG = False
23     SQLALCHEMY_DATABASE_URI = "mysql://root:hushuai@127.0.0.1:3306/demo"
24     LEVEL_LOG = logging.ERROR
25 class TestConfig(Config):
26     pass
27 #测试工厂
28 configs = {
29     "dev":DevelopmentConfig,
30     "pro":ProductionConfig,
31     "tes":TestConfig,
32 }

接下来是db问题的解决,先看代码

 1 db = SQLAlchemy()
 2 redis_store = None
 3 redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,decode_responses=True)
 4 def create_app(env):
 5     setup_log(configs[env].LEVEL_LOG)
 6 #设置日志等级
 7     app = Flask(__name__)
 8     app.config.from_object(configs[env])
 9 
10     db.init_app(app)
11     global redis_store
12     redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)
13 
14     # CSRFProtect(app)
15     Session(app)
16 
17     from info.modules.index import index_blue
18     app.register_blueprint(index_blue)
19     from info.modules.passport import passport_blue
20     app.register_blueprint(passport_blue)
21 
22     from info.modules.news import news_index
23     app.register_blueprint(news_index)
24     from info.utlis.tools import do_rank
25     app.add_template_filter(do_rank,"rank")
26     return app

我们这里是已经解决好db问题的代码,就是用db.init_app(app)来解决的

原文地址:https://www.cnblogs.com/Hdwmsyqdm/p/13864538.html