flask wsgi file configuration

I have created a flask app.I want to run this both development and production server. This is my app.py file:

app = Flask(__name__)

db = SQLAlchemy(app)

app.config.from_object(Config)
db.init_app(app)

if __name__ == "__main__":
    app.run()

this is my wsgi.py file:

from app import app as application

app = application

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

I want to know if my wsgi configurtion is ok or is it the right way to do it.How can i make sure my production server will run wsgi.py file with the production database configuration?In local i am getting this warning Use a production WSGI server instead.the way i configured willl it ensure it will run on wsgi server in prodcution?While i run this command:

uwsgi --wsgi-file app.py --http :5000

i am getting internal server error in localhost:5000.


Solution 1:

One way of handling this is by having a configuration file (config.py) that contains classes for each environment. Then within each of your environments, you'd have a .env file that contains environment-specific variables, such as database URIs, secret keys, etc.

Example config file:

from os import environ, path
from dotenv import load_dotenv

basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))


class Config:
    """Base config."""
    SECRET_KEY = environ.get('SECRET_KEY')
    SESSION_COOKIE_NAME = environ.get('SESSION_COOKIE_NAME')
    STATIC_FOLDER = 'static'
    TEMPLATES_FOLDER = 'templates'


class ProdConfig(Config):
    FLASK_ENV = 'production'
    DEBUG = False
    TESTING = False
    DATABASE_URI = environ.get('PROD_DATABASE_URI')


class DevConfig(Config):
    FLASK_ENV = 'development'
    DEBUG = True
    TESTING = True
    DATABASE_URI = environ.get('DEV_DATABASE_URI')

Then, in your application, you can specify which config class you'd like to load.

ENV = environ.get("environment")

# Using a production configuration
if ENV=='PROD':
    app.config.from_object('config.ProdConfig')

# Using a development configuration
if ENV=='PROD':
    app.config.from_object('config.DevConfig')

For more details, Flask has some docs on this situation