Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with flask config usage. Having a KeyError when accessing a configuration item

Tags:

python

flask

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

like image 401
black sensei Avatar asked Sep 07 '25 15:09

black sensei


1 Answers

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.

like image 109
GG_Python Avatar answered Sep 10 '25 04:09

GG_Python