flask中config
def get_db_uri(dbinfo): ENGINE = dbinfo.get("ENGINE") or 'mysql' DRIVER = dbinfo.get("DRIVER") or "pymysql" USER = dbinfo.get("USER") or "root" PASSWORD = dbinfo.get("PASSWORD") or "cjsoft100" HOST = dbinfo.get("HOST") or "cdb-pi42xze4.bj.tencentcdb.com" PORT = dbinfo.get("PORT") or "10091" NAME = dbinfo.get("NAME") or "develop" print("{}+{}://{}:{}@{}:{}/{}".format(ENGINE, DRIVER, USER, PASSWORD, HOST, PORT, NAME)) return "{}+{}://{}:{}@{}:{}/{}".format(ENGINE, DRIVER, USER, PASSWORD, HOST, PORT, NAME) class Config: DEBUG = False TESTING = False SECRET_KEY = "dsgsdhsa" SQLALCHEMY_TRACK_MODIFICATIONS = False class DevelopConfig(Config): DEBUG = True DATABASE = { "ENGINE": "mysql", "DRIVER": "pymysql", "USER": "root", "PASSWORD": "123456", "HOST": "127.0.0.1", "PORT": "3306", "NAME": "shop" } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) class TestingConfig(Config): TESTING = True DATABASE = { "ENGINE": "mysql", "DRIVER": "pymysql", "USER": "root", "PASSWORD": "cjsoft100", "HOST": "cdb-pi42xze4.bj.tencentcdb.com", "PORT": "10091", "NAME": "shop" } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) class StagingConfig(Config): DATABASE = { "ENGINE": "mysql", "DRIVER": "pymysql", "USER": "root", "PASSWORD": "cjsoft100", "HOST": "cdb-pi42xze4.bj.tencentcdb.com", "PORT": "10091", "NAME": "shop" } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) class ProductConfig(Config): DATABASE = { "ENGINE": "mysql", "DRIVER": "pymysql", "USER": "root", "PASSWORD": "cjsoft100", "HOST": "cdb-pi42xze4.bj.tencentcdb.com", "PORT": "10091", "NAME": "shop" } SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE) envs = { "develop": DevelopConfig, "testing": TestingConfig, "staging": StagingConfig, "product": ProductConfig, "default": DevelopConfig }
其实最终是把数据库的一些账号密码写成类的形式:
class Config: DEBUG = False TESTING = False SECRET_KEY = "dsgsdhsa" SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}".format(ENGINE, DRIVER, USER, PASSWORD, HOST, PORT, NAME)
然后用app.config.from_object(Config)
from flask import Flask class Config: DEBUG = False TESTING = False SECRET_KEY = "dsgsdhsa" SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}".format(ENGINE, DRIVER, USER, PASSWORD, HOST, PORT, NAME) def create_app(Config): app = Flask(__name__) # 用from_object方法写入配置类 app.config.from_object(Config) return app create_app(Config)
全世界的程序员们联合起来吧!