Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Let's say your Flask app has the following structure.
├── main.py
├── database (directory)
│ ├── example.db
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── models.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── results.html
│ └── static (directory)
│ └── custom.css
In your controller (__init__,py in this example), set a SECRET_KEY, which is used to "salt" a hashed password.
app.config['SECRET_KEY'] = 'some_random_string_of_data'
In your view (views.py in this example), import session, and create a session key and value.
from flask import render_template, session
@views.route('/')
def home():
session["foo"] = "bar"
return render_template('home.html')
In this example, the home.html template is rendered. Here is how you could use the session value in HTML.
{% extends "base.html" %}
{% block content %}
{% if session.foo %}
session.foo contains a value of {{ session.foo }}
{% else %}
session.foo does not exist
{% endif %}
{% endblock %}
And here is how you can do something based on the value of a session key in Python.
@views.route('/test')
def test():
try:
session.get('foo')
except KeyError:
return "session.get('foo') raised KeyError"
else:
print("session foo = " + str(session.get('foo'))
if session.get('foo') == 'bar':
return "session foo equals bar"
else:
return "session food does not equal bar"
Or, as a bit of a more practical example, here is how you could create a session when a user signs in, and clear sessions when a user signs out.
from flask import render_template, session
@views.route('/signin')
def signin():
session["signedin"] = True
return render_template('home.html')
@views.route('/signout')
def signout():
session.clear()
return render_template('home.html')
Did you find this article helpful?
If so, consider buying me a coffee over at