Flask Request Object III - Cookies

Cookies:

def setcookie(): define a cookie created and stored function
make_response(): get response object from return value of a view function
set(): from response object to store a cookie

def getcookie(): define a read cookie function
get(): from request.cookies to read a cookie

example:

vi templates/cookie.html

<html>
   <body>
     
<!--
         <form action = "http://<ip/url>/setcookie" method = "POST">
      -->
      <form action = "/setcookie" method = "POST">
         <p><h3>Enter
User Name</h3></p>
         <p><input type = 'text' name = 'Name'/></p>
         <p><input type = 'submit' value = 'Login'/></p>
      </form>

   </body>
</html>
vi cookie.py
from flask import Flask, render_template, request, make_response
ap = Flask(__name__)

@ap.route('/')
def cookie():
   return render_template('cookie.html')

@ap.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
   if request.method == 'POST':
       user = request.form['Name']

   resp = make_response(render_template('readcookie.html'))
   resp.set_cookie('UserName', user)

   return resp

@ap.route('/getcookie')
def getcookie():
   name = request.cookies.get('
UserName')
   return '<h1>Hello '+name+'</h1>'

if __name__ == '__main__':
   ap.run(host= '0.0.0.0')
vi templates/readcookie.html
<html>
  <body>

    <a href="http://<ip/url>:5000/getcookie">Enter</a>
   
<!--
     
<a href="/getcookie">Enter</a>
     -->
  </body>
</html>
python cookie.py

#open http://<ip/url>:5000



Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved