问题
In my Flask application's config.py
i have LocalConfig
and ProdConfig
and latter is to be used in production, once app is deployed.
Now i'm using uWsgi
to serve app to Nginx
and here the myapp.wsgi
i have created.
from myapp import create_app
from myapp.config import ProdConfig
app = create_app(config=ProdConfig)
and in one of other app.py
create_app
is defined as:
def create_app(config=None, app_name=None, blueprints=None):
# some code
app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True)
configure_app(app, config)
# some other code
return app
def configure_app(app, config=None):
"""Different ways of configurations."""
app.config.from_object(LocalConfig)
app.config.from_pyfile('production.cfg', silent=True)
if config:
app.config.from_object(config)
I want to know, will it properly with uWSGI
? Will uWSGI be able to applying the ProdConfig
successfully?
Or is it better to use Environment Variables to distinguish between different config settings? Like if os.environ.get('PROD', True): #do something
?
Which way is better? Flask's create_app()
one or the env variable one? Any other suitable approach?
回答1:
A common way of doing this is storing the configurations in a dictionary.
class Config:
ALL_CAPS_CONFIG = 'SOME VALUE'
class DevConfig(Config):
pass
class TestConfig(Config):
pass
class ProdConfig(Config):
pass
configs = {
'dev' : DevConfig,
'test' : TestConfig,
'prod' : ProdConfig,
'default' : ProdConfig
}
And then where you actually create your app, you'd do something like this::
from config import configs
import os
evn = os.environ.get('MY_FLASK_APP_ENV', 'default')
create_app(config=configs[evn])
That way you can easily switch between the environments by changing a variable in your shell.
回答2:
It is actually much nicer to point an environment variable to a completely separate config.py file. Personally I have a config.py file that contains my base and development settings, then another config.py for my production configuration, the location of which is specified from an environment variable.
I would recommend that you look at the Flask Configuration documentation, as it does a good job at explaining how the configuration files should be setup.
来源:https://stackoverflow.com/questions/25745390/how-to-serve-different-config-settings-in-flask-app-to-uwsgi-using-create-app