In this Flask tutorial we are going to learn How to Work with Cookies in Flask, so cookies are small piece of data stored on the user’s computer by the web browser while browsing a website. Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user’s browsing activity, basically in this lesson we want to learn how you can set and get cookies in flask.
This is our app.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
from flask import Flask, make_response, request #create the object of Flask app = Flask(__name__) #creating our routes @app.route('/') def Index(): return "<h1>Geekscoders.com, Hello Flask Application</h1>" @app.route('/contact') def Contact(): return "<h1>Geekscoders.com, Contact Page</h1>" @app.route('/about') def About(): return "<h1>Geekscoders.com, About Page</h1>" #passing parametrs to the routes @app.route('/user/<name>') def User(name): return "<h1>Welcome to : {}</h1>".format(name) @app.route('/set') def setCookie(): response = make_response("i have set the cookie") response.set_cookie("myapp", "Flask Web Development") return response @app.route('/get') def getCookie(): myapp = request.cookies.get("myapp") return "Cookie Content Is " + str(myapp) #run flask app if __name__ == "__main__": app.run(debug=True) |
We have created two new routes one for setting the cookie, in this route you can use set_cookie() method from response, you need to give the cookie name and the cookie value.
1 2 3 4 5 6 |
@app.route('/set') def setCookie(): response = make_response("i have set the cookie") response.set_cookie("myapp", "Flask Web Development") return response |
The second route is for getting the cookie.
1 2 3 4 |
@app.route('/get') def getCookie(): myapp = request.cookies.get("myapp") return "Cookie Content Is " + str(myapp) |
Now first you need to set the cookie, http://localhost:5000/set
And after that you can get the cookie, http://localhost:5000/get
