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
Flask gives us the ability to choose a configuration file on load based on the value of an environment variable. This means that we can have several configuration files in our repository and always load the right one. Once we have several configuration files, we can move them to their own config directory.
secret key is a random key used to encrypt your cookies and save send them to the browser. This error is because of this line in the Flask-Debugtoolbar code. To fix this you just need to set a SECRET_KEY in your config file. app.config['SECRET_KEY'] = "Your_secret_string"
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.
After a little bit of fiddling (and a little help from the 'net), I could improve this further, by changing the code to include the config to:
app.config.from_object('config.ProductionConfig')
This enables this cool pattern for configurations:
class Config(object): DEBUG = True DEVELOPMENT = True SECRET_KEY = 'do-i-really-need-this' FLASK_HTPASSWD_PATH = '/secret/.htpasswd' FLASK_SECRET = SECRET_KEY DB_HOST = 'database' # a docker link class ProductionConfig(Config): DEVELOPMENT = False DEBUG = False DB_HOST = 'my.production.database' # not a docker link
What's left now is to see how to integrate testing configs into this, but at least it feels less clumsy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With