article

Saturday, June 11, 2016

Python Flask - Sending Form Data to Template and Cookies

Python Flask - Sending Form Data to Template and Cookies
 
Flask – Sending Form Data to Template

In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to table.html.
 
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('student.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/
#if click submet call result http://127.0.0.1:5000/result   
Given below is the HTML script of student.html.

   
      
Name
Physics
Chemistry
Maths

Code of template (result.html) is given below −

   
      
         {% for key, value in result.iteritems() %}

{% endfor %}
      
{{ key }} {{ value }}
Flask – Cookies
A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie.
from flask import Flask, render_template, request,make_response
app = Flask(__name__)

@app.route('/') # http://localhost:5000/
def index():
   return render_template('index.html')
 
@app.route('/setcookie', methods = ['POST', 'GET']) # http://localhost:5000/setcookie
def setcookie():
   if request.method == 'POST':
      user = request.form['nm']
    
   resp = make_response(render_template('readcookie.html'))
   resp.set_cookie('userID', user)
    
   return resp
 
@app.route('/getcookie') # http://localhost:5000/getcookie
def getcookie():
   name = request.cookies.get('userID')
   return '

welcome '+name+'

' if __name__ == '__main__': app.run(debug = True)
index.html

   
      

Enter userID




Related Post