

{"id":113247,"date":"2023-07-26T19:04:18","date_gmt":"2023-07-26T13:34:18","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=113247"},"modified":"2023-07-26T19:04:09","modified_gmt":"2023-07-26T13:34:09","slug":"flask-cookies","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/flask-cookies\/","title":{"rendered":"Flask Cookies"},"content":{"rendered":"<p>In this article, we will learn about cookies in flask, how to set, get and remove cookies and much more. Let&#8217;s start!!!<\/p>\n<h3>Flask Cookies<\/h3>\n<p>Python was used to create the lightweight Flask web development framework. Normally, we use HTML, CSS, and JavaScript to create websites, but flask uses the Python programming tool to develop web apps.<\/p>\n<p>When you visit a website, cookies are small text files that the website saves to your mobile device or computer. To make it run better and offer services catered to our interests, the cookie stores data about our visit. Additionally, cookies can be used to save user settings like translation or regional preferences. Cookies benefit users by improving their experience, increasing website efficiency, and identifying returning users.<\/p>\n<p>On the client&#8217;s computer, the cookies are kept as text files. Cookie is implemented to track a user&#8217;s online activity and display suggestions based on the user&#8217;s preferences to improve the user experience.<\/p>\n<p>Cookies are placed on the client&#8217;s computer by the server and linked to their requests to that host in subsequent transactions until the cookie expires or is deleted.<\/p>\n<p>In Flask, the dictionaries collection of all cookie parameters and associated values sent by the client is connected to the Requests object as the cookie object. We may provide the website&#8217;s domain name, path, and expiration time with the help of Flask.<\/p>\n<p>A text file in the format of a cookie is kept on a client&#8217;s computer. To improve user satisfaction and site statistics, it is designed to store and track information about a client&#8217;s usage.<\/p>\n<p>An attribute of a cookie can be found in a Request object. A user has sent a dictionary object that contains all of the cookies variables and their respective values. A cookie also keeps track of the site&#8217;s domain name, path, and expiration time.<\/p>\n<p>Cookie is set on the response object in Flask. To obtain a response object from a view function&#8217;s return value, use the make response() function. After that, you can store a cookie using the response object&#8217;s set cookie() function.<br \/>\nIt&#8217;s simple to read a cookie back. the request method get(). To read a cookie, use the cookies attribute.<\/p>\n<h3>Setting Cookies in Flask<\/h3>\n<p>The set cookie() function on the return object in Flask is used to set cookies on the object. The make response() function in the view procedure can be used to create the response object.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import *  \r\napp = Flask(__name__)  \r\n@app.route('\/method')  \r\ndef method():  \r\n    res = make_response(\"&lt;h1&gt;Setting Cookies&lt;\/h1&gt;\")  \r\n    res.set_cookie('foo','bar')  \r\n    return res  \r\nif __name__ == '__main__':  \r\n    app.run(debug = True)  \r\n<\/pre>\n<p>The python script mentioned above can be used to create a cookie on the computer for the localhost:5000 website with the name &#8220;foo&#8221; and the content &#8220;bar.&#8221; Execute this Python code by typing python script.py, then check the browser for the outcome.<\/p>\n<h3>Removal of cookies from the flask<\/h3>\n<p>Cookies may also be deleted. To delete a cookie, use set cookie() with any value and the max age argument set to 0. Just after cookie() view function in the server.py file, add the following code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">@app.route('\/delete-cookie\/')\r\ndef remove():\r\n    res = make_response(\"Successfully Removed Cookie.\")\r\n    res.set_cookie('foo', 'bar', max_age=0)\r\n    return res\r\n<\/pre>\n<h3>How to get cookies in flask<\/h3>\n<p>This get() method uses the request object to acquire the cookie value from the user&#8217;s web browser.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, request, make_response\r\napp = Flask(__name__)\r\n# getting cookie from the previous set_cookie code\r\n@app.route('\/get')\r\ndef get():\r\n    Data = request.cookies.get('Data')\r\n    return 'You have some access to '+ Data\r\napp.run()\r\n<\/pre>\n<h3>Application for Flask Login<\/h3>\n<p>Here, we&#8217;ll build a login application using Flask, where the user is presented with a login screen (login_page.html) that asks them to input their email and password. The application will send the client to the victory page (success.html), in which the greeting and a hyperlink to the account (account.html) are provided, if indeed the password is &#8220;jtp,&#8221; else it will send them to the error page.<\/p>\n<p><strong>login_page.py<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import *  \r\napp = Flask(__name__)  \r\n@app.route('\/error')  \r\ndef error():  \r\n    return \"&lt;p&gt;&lt;strong&gt;Enter your password&lt;\/strong&gt;&lt;\/p&gt;\"  \r\n@app.route('\/')  \r\ndef login_fun():  \r\n    return render_template(\"login_page.html\")  \r\n@app.route('\/success',methods = ['POST'])  \r\ndef success():  \r\n    if request.method == \"POST\":  \r\n        email = request.form['email']  \r\n        password = request.form['pass']  \r\n    if password==\"jtp\":  \r\n        resp = make_response(render_template('successful.html'))  \r\n        resp.set_cookie('email',email)  \r\n        return resp  \r\n    else:  \r\n        return redirect(url_for('error'))  \r\n@app.route('\/profile_view')  \r\ndef account():  \r\n    email = request.cookies.get('email')  \r\n    resp = make_response(render_template('account.html',name = email))  \r\n    return resp  \r\nif __name__ == \"__main__\":  \r\n    app.run(debug = True)\r\n<\/pre>\n<p><strong>login_page.html<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;html&gt;  \r\n&lt;head&gt;  \r\n    &lt;title&gt;Login page&lt;\/title&gt;  \r\n&lt;\/head&gt;  \r\n&lt;body&gt;  \r\n    &lt;form method = \"post\" action = \"http:\/\/localhost:5000\/success\"&gt;  \r\n        &lt;table&gt;  \r\n            &lt;tr&gt;&lt;td&gt;Email Id&lt;\/td&gt;&lt;td&gt;&lt;input type = 'email' name = 'email'&gt;&lt;\/td&gt;&lt;\/tr&gt;  \r\n            &lt;tr&gt;&lt;td&gt;enter Password&lt;\/td&gt;&lt;td&gt;&lt;input type = 'password' name = 'pass'&gt;&lt;\/td&gt;&lt;\/tr&gt;  \r\n            &lt;tr&gt;&lt;td&gt;&lt;input type = \"submit\" value = \"Submit\"&gt;&lt;\/td&gt;&lt;\/tr&gt;  \r\n        &lt;\/table&gt;  \r\n    &lt;\/form&gt;  \r\n&lt;\/body&gt;  \r\n&lt;\/html&gt; \r\n<\/pre>\n<p><strong>success.html<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;html&gt;  \r\n&lt;head&gt;  \r\n&lt;title&gt;Successful&lt;\/title&gt;  \r\n&lt;\/head&gt;  \r\n&lt;body&gt;  \r\n    &lt;h2&gt;Successfully Logged In.&lt;\/h2&gt;  \r\n    &lt;a href=\"\/viewprofile\"&gt;View Profile&lt;\/a&gt;  \r\n&lt;\/body&gt;  \r\n&lt;\/html&gt;  \r\n<\/pre>\n<p><strong>account.html<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;html&gt;  \r\n&lt;head&gt;  \r\n    &lt;title&gt;Account&lt;\/title&gt;  \r\n&lt;\/head&gt;  \r\n&lt;body&gt;  \r\n    &lt;h3&gt;Hello, {{name}}&lt;\/h3&gt;  \r\n&lt;\/body&gt;  \r\n&lt;\/html&gt;\r\n<\/pre>\n<h3>Counting website visitors with cookies<\/h3>\n<p>The code below asks for the quantity of people who have visited our website. By using cookies, we first retrieve the number of visitors. However, the visitor count variable we previously made does not exist. According to the database collection in Python, this key (visitors count) would take the value of zero since it is not existent in the dictionary. As a result, the count is increased when a user visits the page, starting at 0 for first-time users. The response object is obtained by using make response(), which is also where the cookie is set.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, request, make_response\r\napp = Flask(__name__)\r\napp.config['DEBUG'] = True\r\n@app.route('\/')\r\ndef vistors_count():\r\n    # Conversion of string to integer\r\n    num = int(request.cookies.get('visitors count', 0))\r\n    # Getting the key-visitors count value as 0\r\n    num = num+1\r\n    output = 'You visited this page for '+str(num) + ' times'\r\n    resp = make_response(output)\r\n    resp.set_cookie('visitors count', str(num))\r\n    return resp\r\n@app.route('\/get')\r\ndef count():\r\n    num = request.cookies.get('visitors count')\r\n    return num\r\napp.run()\r\n<\/pre>\n<h3>Creating a cookie in flask:<\/h3>\n<p>In Flask, creating a cookie is a straightforward process that involves using the set_cookie() method provided by the make_response() function. Here is an example code snippet that demonstrates how to create a cookie in Flask:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, make_response\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('\/')\r\ndef index():\r\n    resp = make_response('Setting a cookie')\r\n    resp.set_cookie('my_cookie', 'cookie_value')\r\n    return resp\r\n\r\nif __name__ == '__main__':\r\n    app.run()\r\n<\/pre>\n<p>In the above example, we import the Flask library and the make_response() function that is used to create a response object. We then define a route for the root URL \/ and create a response object using the make_response() function with the message &#8220;Setting a cookie&#8221;.<\/p>\n<p>Next, we call the set_cookie() method on the response object to set the cookie with the name &#8216;my_cookie&#8217; and value &#8216;cookie_value&#8217;. Finally, we return the response object to the user.<\/p>\n<p>When the user visits the URL, the server will respond with the message &#8220;Setting a cookie&#8221; and also set a cookie with the name &#8216;my_cookie&#8217; and value &#8216;cookie_value&#8217;. The browser will then store the cookie and send it back to the server with subsequent requests to that host until the cookie expires or is deleted.<\/p>\n<p>Overall, creating cookies in Flask is a simple process that can be done using the set_cookie() method provided by the make_response() function.<\/p>\n<h3>Conclusion<\/h3>\n<p>On the client&#8217;s computer, cookies are saved as text files. In order to improve visitors \u2019 experience and website statistics, the goal is to recall and track data pertinent to consumer usage. The cookie&#8217;s properties are contained in the Flask Request object. The client is moved, and it is a dictionary object containing all cookie parameters and their respective values.<\/p>\n<p>We utilise cookies to save and track user activity to enhance their experience on the site. They also keep track of details like the site&#8217;s domain, route, and expiration date.<\/p>\n<p>Websites like Facebook keep you signed in even after you leave, allowing seamless access on your next visit. You often receive suggestions for various products on eCommerce websites depending on the search history of your browser. Cookies also save information about the website&#8217;s domain name, route, and expiration date.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about cookies in flask, how to set, get and remove cookies and much more. Let&#8217;s start!!! Flask Cookies Python was used to create the lightweight Flask web development&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114832,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27373],"tags":[27634],"class_list":["post-113247","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-flask-tutorials","tag-cookies-in-flask"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Flask Cookies - DataFlair %<\/title>\n<meta name=\"description\" content=\"Cookies help to save and track user activity to enhance their experience on the site. Learn how to get, set and remove cookies.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/flask-cookies\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Flask Cookies - DataFlair %\" \/>\n<meta property=\"og:description\" content=\"Cookies help to save and track user activity to enhance their experience on the site. Learn how to get, set and remove cookies.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/flask-cookies\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-07-26T13:34:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Flask Cookies - DataFlair %","description":"Cookies help to save and track user activity to enhance their experience on the site. Learn how to get, set and remove cookies.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/flask-cookies\/","og_locale":"en_US","og_type":"article","og_title":"Flask Cookies - DataFlair %","og_description":"Cookies help to save and track user activity to enhance their experience on the site. Learn how to get, set and remove cookies.","og_url":"https:\/\/data-flair.training\/blogs\/flask-cookies\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-07-26T13:34:18+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Flask Cookies","datePublished":"2023-07-26T13:34:18+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/"},"wordCount":1054,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp","keywords":["cookies in flask"],"articleSection":["Python Flask Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/flask-cookies\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/","url":"https:\/\/data-flair.training\/blogs\/flask-cookies\/","name":"Flask Cookies - DataFlair %","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp","datePublished":"2023-07-26T13:34:18+00:00","description":"Cookies help to save and track user activity to enhance their experience on the site. Learn how to get, set and remove cookies.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/flask-cookies\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/flask-cookies.webp","width":1200,"height":628,"caption":"flask cookies"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/flask-cookies\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Flask Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python-flask-tutorials\/"},{"@type":"ListItem","position":3,"name":"Flask Cookies"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113247","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=113247"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113247\/revisions"}],"predecessor-version":[{"id":116933,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113247\/revisions\/116933"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114832"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=113247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=113247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=113247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}