Is there a way to config flask app port in config file?

Viewed 1787

I'm learning Python Flask and I'm codding a simple web app with comments section, login and create user section. I'm stuck after a few lessons. I've created a config.py file to add all the app configs inside it like ENV name, DEBUG, SECRET_KEY but I don't find any way to set-up port number in this file. I write in the config class PORT = 8000 but my app doesn't recognise this, I have to set-up it in run.py file "app.run(port = 8000)".

Do you have any idea? Thanks :)

Config.py:

import os

class Config(object):
    SECRET_KEY = 'secretkeyforsessions'

class DevelopmentConfig(Config):
    #PORT = 8000
    #port = 8000
    ENV = "development"
    DEBUG = True
    SQLAlCHEMY_DATABASE_URI = "mysql://root:root@localhost/flask"
    SQLALCHEMY_TRACK_MODIFICATIONS = False

run.py:

if __name__ == '__main__': 
    csrf.init_app(app)
    """
    db.init_app(app)
    with app.app_context():
        db.create_all() # Se encarga de crear todas las tablas que no sean creadas
    """
    app.run(port = 8000)
1 Answers

Flask offers app.config.from_object('...a config file') https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-files

# config.py
ENV = "development"
PORT = "8000"
DEBUG = True

SECRET_KEY = 'secretkeyforsessions'

SQLAlCHEMY_DATABASE_URI = "mysql://root:root@localhost/flask"
SQLALCHEMY_TRACK_MODIFICATIONS = False

and

# run.py
# ...
import config

app.config.from_object(config)
print(app.config)

app.run(port=config.PORT)

# ...
Related