3

In my main.py have the below code:

app.config.from_object('config.DevelopmentConfig')

In another module I used import main and then used main.app.config['KEY'] to get a parameter, but Python interpreter says that it couldn't load the module in main.py because of the import part. How can I access config parameters in another module in Flask?

Alireza
  • 6,497
  • 13
  • 59
  • 132
  • Does this answer your question? [Access config values in Flask from other files](https://stackoverflow.com/questions/32017527/access-config-values-in-flask-from-other-files) – zs2020 Apr 28 '21 at 06:37

2 Answers2

1

Your structure is not really clear but by what I can get, import your configuration object and just pass it to app.config.from_object():

from flask import Flask
from <path_to_config_module>.config import DevelopmentConfig

app = Flask('Project')
app.config.from_object(DevelopmentConfig)

if __name__ == "__main__":
    application.run(host="0.0.0.0")

if your your config module is in the same directory where your application module is, you can just use :

from .config import DevelopmentConfig
Taxellool
  • 4,063
  • 4
  • 21
  • 38
1

The solution was to put app initialization in another file (e.g: myapp_init_file.py) in the root:

from flask import Flask
app = Flask(__name__)

# Change this on production environment to: config.ProductionConfig
app.config.from_object('config.DevelopmentConfig')

Now to access config parameters I just need to import this module in different files:

from myapp_init_file import app

Now I have access to my config parameters as below:

app.config['url']

The problem was that I had an import loop an could not run my python app. With this solution everything works like a charm. ;-)

Alireza
  • 6,497
  • 13
  • 59
  • 132