I have made sure I read all possible post about this but it seems something is still blurred to me. I am learning python by doing a project with flask. My folder structure is as shown below
/source
/config
__init__.py
settings.py
/classes
__init__.py
Dblayer.py
/templates
index.html
test.html
myapp.py
So in my app I am using the following
from flask import Flask, request, session, g, redirect, url_for, abort, render_template
from classes import DbLayer
app = Flask(__name__)
app.config.from_pyfile("config/settings.py") # this is according to documentation...so I am confused
@app.route('/')
def index():
return render_template("index.html")
@app.route('/viewitems')
def showitems():
return render_template("test.html", db= app.config['host'])
The content of settings.py is really simple:
database = "somedb"
username = "someuser"
password = "somepassword"
host = "localhost"
I used test.html to see the usage of the configuration in flask and I am having a very annoying KeyError: 'host'. Is there anything that I am not doing well?
Thanks
From the docs:
Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys.
It's easy to miss.
Rename your config variables using uppercase only.
Another thing to note is that you don't have to pass the config variable, nor any specific value in that dictionary to the jinja2 templating engine. Flask exposes them. Basically, get rid of db= app.config['host']
, config['host'], and all other config variables are already available in all templates.. See here for more details.
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