Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - How to import from config file in Flask?

I have followed the layout of my Flask project from http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world.

I have the following structure:

app/
    __init__.py
    views.py
    forms.py
    myFile.py
run.py
config.py

In views.py, forms.py I am able to use

from config import basedir

However I cannot use that in myFile.py

I added

import Flask 

and when I modify it, the Flask web server restarts, but it doesn't say found changes in app/myFile.py restarting it just restarts.

What do I need to do to be able to use

from config import basedir

in my python file. I don't see anything special being done in __init__.py for forms.py.

EDIT: This is my __init__.py file:

from flask import Flask
from config import basedir

app = Flask(__name__)
app.config.from_object('config')
from app import views
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When people talk about configs in Flask, they are generally talking about loading values into the app's configuration. In your above example you could have something like app.config.from_object('config') in your init.py file. Then all the configuration values will be loaded into the app.config dictionary.

Then in any of your files you could just import the app object to gain access to that dictionary. I tend to access that app object by doing from flask import current_app as app then just app.config['MY_SETTING'] to get the value I care about. Read up more in the documenation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...