有很多方法,推崇的方法是:
app.config.from_object('pro_flask.settings.TestingConfig')
settings.py
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
PS: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为
True
,则就是instance_path目录
PS: 从sys.path中已经存在路径开始写
优雅的编程例子:
目录结构:
app.py
from flask import Flask,request
from utils.message import send_msg
app = Flask(__name__)
app.secret_key="ddtegesgee"
@app.route('/index')
def index():
name = request.args.get("name")
if name == "kk":
send_msg('...')
else:
return "error"
if __name__ == '__main__':
app.run()
settings.py
MSG_LIST = [
"utils.message.email.Email",
"utils.message.msg.Message"
]
message包中 base.py
class Base(object):
def send(self):
raise NotImplementedError('...')
message包中 email.py
from .base import Base
class Email(Base):
def send(self):
pass
message包中 msg.py
from .base import Base
class Message(Base):
def send(self):
pass
message包中 __init__.py
import settings
import importlib
def send_msg(msg):
for path in settings.MSG_LIST:
module_name,func_name = path.rsplit('.',maxsplit=1)
module = importlib.import_module(module_name)
obj = getattr(module,func_name)()
obj.send(msg)