article

Saturday, June 11, 2016

Python Flask HTTP Method, Templates, Static Files

Python Flask

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.

The following table summarizes different http methods −

GET
Sends data in unencrypted form to the server. Most common method.   
HEAD
Same as GET, but without response body   
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.   
PUT
Replaces all current representations of the target resource with the uploaded content.   
DELETE
Removes all current representations of the target resource given by a URL

demonstrate the use of POST method in URL routing


   
      
      
Enter Name:
Now enter the following script in Python shell.
 
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)
Flask – Templates
Jinja2 template. HTML file can be engine rendered by the render_template() function
 
from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
   app.run(debug = True)
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
Application folder
  • Hello.py
  • templates
    • hello.html
The following code is saved as hello.html in the templates folder.

   
      

Hello {{ name }}!

Next, run the following script from Python shell.
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost:5000/hello/tutorial101
The variable part of URL is inserted at {{ name }} place holder.

The Jinga2 template engine uses the following delimiters for escaping from HTML.

{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements

following example, use of conditional statement in the template is demonstrated.

 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost/hello/60
HTML template script of hello.html is as follows −

   
   
      {% if marks>50 %}
      

Your result is pass!

{% else %}

Your result is fail

{% endif %} Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}
Flask – Static Files
A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. these files are served from static folder in your package or next to your module and it will be available at /static on the application. In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)
   
   
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)
The HTML script of index.html is given below.

   
      
   
   
      
   

Hello.js contains sayHello() function.
 function sayHello() {
   alert("Hello World")
}

Related Post