1. 程式人生 > 實用技巧 >1.1 app工廠以及db問題的解決

1.1 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:[email protected]: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:[email protected]: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)來解決的