Flask setting cookies

share link

by vsasikalabe dot icon Updated: Mar 8, 2023

technology logo
technology logo

Solution Kit Solution Kit  

On Netflix or shop at Amazon, or when logged into some website, we can see the "remember me" button. Based upon your search, it saves your personal information for recommending products. In a database storing the personalized info of every user is time-consuming. We keep a site's cookies in the user's browser. When visiting a website, cookies save files on your computer or mobile device. 


Flask uses built-in cookie functionality to store session cookies and makes them available to our viewers. This allows the ability to remember the state of a user between browser sessions, such as the ability to remember a logout state or user's preferences. A request object is a powerful tool in Flask. It makes all sorts of advanced web requests. For accessing the request object, the Flask provides a convenient wrapper. This object represents the current HTTP request. The response object of Flask is cookies. With the make_response()method, we must initialize a response object and then attach the cookie key. This has done by the set_cookie() command (value pair to this object).  

A cookie also stores its expiry time, path, and the main name of the site. Cookies are set on the response in the Flask object.SECRET_KEY: Flask "secret keys" store sensitive user data, such as passwords. To get the response object from the view function, use the make_response() function. Using the set_cookie() function, the cookies are stored. It is easy to read back cookies. The HTML file stores the code for getting buttons, login or logout messages, and input text areas. If the login details are correct, the corresponding message will be displayed. Otherwise, it shows 'wrong username or password' or 'danger.' 


Here is an example of how to set cookies using Flask: 

Preview of the output that you will get on running this code from your IDE.

Code

In this solution we used flask library of python.

from flask import Flask, render_template, request, make_response, flash, redirect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'SUPER SECRET'

@app.route('/', methods = ['GET'])
def home():
    username = request.cookies.get('username')
    if username:
        return render_template('home.html', username=username)
    return render_template('home.html')

@app.route('/login', methods = ['GET','POST'])
def login():
    username = request.cookies.get('username')
    if username:
        return render_template('login.html', username=username)
    if request.method=='POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if username=='admin' and password=='admin':
            flash("Successful login", "success")
            resp = make_response(redirect('/'))
            resp.set_cookie('username', username)
            return resp
        else:
            flash("Wrong username or password", "danger")
    return render_template('login.html')

@app.route('/logout', methods = ['GET'])
def logout():
    resp = make_response(redirect('/'))
    resp.delete_cookie('username')
    return resp
app.run(debug=True)

<html>
    <head>
        <title>Home</title>
    </head>
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
        {% if username %}
            Welcome {{ username }}. 
            <a href="{{ url_for('logout') }}">Click here</a> to logout.
        {% else %}
            You are not logged in.          
            <a href="{{ url_for('login') }}">Click here</a> to login.
        {% endif %}
    </body>
</html>

<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}

        {% if username %}
            You are already logged in as{{ username }}.
            <a href="{{ url_for('home') }}">Click here</a> to go to home.
            <a href="{{ url_for('logout') }}">Click here</a> to logout.
        {% else %}
            <form method="post" action="">
                <label for="username">Username</label>
                <input type="text" name="username" id="username"/> 
                <br/>

                <label for="password">Password</label>
                <input type="password" name="password" id="password"/> 
                <br/>

                <input type="submit" name="submit" id="submit" value="Login"/> 
            </form>
        {% endif %}
    </body>
</html>

Instructions

Follow the steps carefully to get the output easily.

  1. Download and Install the PyCharm Community Edition on your desktop.
  2. Install flask on your IDE from python interpreter in setting options.
  3. Create new python file on your IDE.
  4. Copy the snippet using the 'copy' button and paste it in your python file.
  5. Create home.html and login.html file under templates folder.Paste html code into html files.
  6. Run the current file to generate the output.


I hope you found this useful. I have added the link to dependent library, version information in the following sections.


I found this code snippet by searching for ' Flask setting cookies ' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. PyCharm Community Edition 2022.3.1
  2. The solution is created in Python 3.11.1 Version
  3. flask 2.2.2 Version


Using this solution, we can do flask setting cookies.This process also facilities an easy to use, hassle free method to create a hands-on working version of code in python which would help us to do flask setting cookies.

Dependent Libraries

flaskby pallets

Python doticonstar image 63300 doticonVersion:2.2.5doticon
License: Permissive (BSD-3-Clause)

The Python micro framework for building web applications.

Support
    Quality
      Security
        License
          Reuse

            flaskby pallets

            Python doticon star image 63300 doticonVersion:2.2.5doticon License: Permissive (BSD-3-Clause)

            The Python micro framework for building web applications.
            Support
              Quality
                Security
                  License
                    Reuse

                      If you do not have flask library that is required to run this code, you can install it by clicking on the above link.

                      You can search for any dependent library on kandi like flask.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page

                      See similar Kits and Libraries