Bootstrap FreeKB - Flask - Getting Started with Cookies
Flask - Getting Started with Cookies

Updated:   |  Flask articles

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

Flask Sessions and Flask Cookies are similar, the primary difference being

Let's say your Flask app has the following files.

├── main.py
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── foo.html
│   │   ├── bar.html

 

Here is a basic example of how to create a cookie named "foo" with a value of "bar".

from flask import Blueprint, render_template, make_response

blueprint = Blueprint('routes_home', __name__)

@blueprint.route('/')
def home():
    response = make_response(render_template('home.html'))
    response.set_cookie("foo", value="bar")
    return response

 

Now when going to the home page of your Flask app, the "foo" cookie should be added to your web browsers cookies. Well, that was easy!

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ca6edb in the box below so that we can be sure you are a human.