Cookies in Flask
A Cookie is a form of text file which is stored on a client’s computer, whose purpose is to remember and track data pertaining to client’s usage in order to improve the website according to the user’s experience and statistic of webpage.
The Request object contains cookie’s attribute. It is the dictionary object of all the cookie variables and their corresponding values. It also contains expiry time of itself. In Flask, cookie are set on response object.See the example given below:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
HTML code ( index.html )
<html>
<body>
<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>
</body>
</html>
Add this code to the Python file defined above
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('cookie.html'))
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
HTML code ( cookie.html )
<html>
<body>
<a href="/getcookie">Click me to get Cookie</a>
</body>
</html>
Run the above application and visit link on Browser http://localhost:5000/ The form is set to ‘/setcookie’ and function set contains a Cookie name userID that will be rendered to another webpage. The ‘cookie.html’ contains hyperlink to another view function getcookie(), which displays the value in browser.
Introduction to Web development using Flask
Flask is a lightweight and flexible web framework for Python. It’s designed to make getting started with web development quick and easy, while still being powerful enough to build complex web applications. Let’s understand Flask Python in more Detail