Menu Close

How to import from config file in Python Flask?

Codeamend

Sometimes, we want to import from config file in Python Flask.

In this article, we’ll look at how to import from config file in Python Flask.

How to import from config file in Python Flask?

To import from config file in Python Flask, we can use the config.from_object method.

For instance, we write

class Config(object):
    DEBUG = True
    DEVELOPMENT = True
    SECRET_KEY = "secret"
    FLASK_HTPASSWD_PATH = "/secret/.htpasswd"
    FLASK_SECRET = SECRET_KEY
    DB_HOST = "database"


class ProductionConfig(Config):
    DEVELOPMENT = False
    DEBUG = False
    DB_HOST = "my.production.database" 

to create config classes in the config.py file.

Then we write

app.config.from_object("config.ProductionConfig") 

in app.py to load the config from the ProductionConfig class in the config.py file with the app.config.from_object.

app is the Flask app instance.

Conclusion

To import from config file in Python Flask, we can use the config.from_object method.

Posted in Python

You can also read...