Example analysis of Python Flask framework template operation

This article describes the template operation of Python Flask framework with examples. Share with you for your reference, as follows:

Template

In the previous example, the main function of the view function is to generate the response of the request, which is the simplest request. In fact, view functions have two functions: processing business logic and returning response content. In large-scale applications, putting business logic and presentation content together will increase the complexity of code and maintenance cost. The role of the template learned in this section is to assume another role of the view function, that is, to return the response content.
A template is actually a file containing response text, in which placeholders (variables) are used to represent the dynamic part, telling the template engine that its specific value needs to be obtained from the data used. The process of replacing variables with real values and returning the resulting string is called "rendering". Flask uses jinja2 as a template engine to render templates. Jinja2 can recognize all types of variables, including {}.
Jinja2 template engine, render provided by Flask_ The template function encapsulates the template engine, render_ The first parameter of the template function is the file name of the template, and the following parameters are key value pairs, indicating the real value corresponding to the variables in the template.

Jinja2 official document( http://docs.jinkan.org/docs/jinja2/
)

Let's first understand the basic syntax of the template:

    {% if user %}
      {{ user }}
    {% else %}
      hello!
    <ul>
      {% for index in indexs %}
      <li> {{ index }} </li>
    </ul>
    
    

Learn the simple use of the following template by modifying the previous example:

    @app.route('/')
    def hello_itcast():
      return render_template('index.html')
    @app.route('/user/<name>')
    def hello_user(name):
      return render_template('index.html',name=name)
    
    

variable

In the template, {{variable
}}Structure representation variable is a special placeholder that tells the template engine that the value of this position is obtained from the data used when rendering the template; Jinja2 can recognize not only basic types of variables, but also {};

    <span>{{mydict['key']}}</span>
    <br/>
    <span>{{mylist[1]}}</span>
    <br/>
    <span>{{mylist[myvariable]}}</span>
    
    
    from flask import Flask,render_template
    app = Flask(__name__)
    @app.route('/')
    def index():
      mydict = {'key':'silence is gold'}
      mylist = ['Speech', 'is','silver']
      myintvar = 0
      return render_template('vars.html',
                  mydict=mydict,
                  mylist=mylist,
                  myintvar=myintvar
                  )
    if __name__ == '__main__':
      app.run(debug=True)
    
    

Reverse routing:
Flask provides the url_for() auxiliary function, you can use the information saved in the program URL mapping to generate the URL; url_for() receives the view function name as a parameter and returns the corresponding URL;

Such as calling url_for('index ', _external=True) returns the absolute address, which is in the following example
http://localhost:5000/ .

Such as calling url_for('index ', name =' apple ', _external=True) Returns:
http://localhost:5000/index/apple :

    @app.route('/')
    def hello_itcast():
      return render_template('index.html')
    @app.route('/user/<name>')
    def hello_user(name):
      return url_for('hello_itcast',_external=True)
    
    

Custom error page:

    from flask import Flask,render_template
    @app.errorhandler(404)
    def page_not_found(e):
      return render_template('404.html'), 404
    
    

filter:

The essence of filter is function. Sometimes we not only need to output the value of the variable, but also need to modify the display of the variable, even formatting, operation, etc., which uses the filter. The usage of the filter is variable name
|Filter. The filter name is written after the variable name, separated by |. For example: {{variable|
capitalize}, the function of this filter: convert the first letter of the value of variable to uppercase and other letters to lowercase. Other commonly used filters are as follows:

safe: disable escape;

    <p>{{ '<em>hello</em>' | safe }}</p>
    
    

capitalize: convert the first letter of the variable value to uppercase and the other letters to lowercase;

    <p>{{ 'hello' | capitalize }}</p>
    
    

lower: convert the value to lowercase;

    <p>{{ 'HELLO' | lower }}</p>
    
    

upper: convert the value to uppercase;

    <p>{{ 'hello' | upper }}</p>
    
    

title: capitalize the first letter of each word in the value;

    <p>{{ 'hello' | title }}</p>
    
    

trim: remove the leading and trailing spaces of the value;

    <p>{{ ' hello world ' | trim }}</p>
    
    

reverse: String inversion;

    <p>{{ 'olleh' | reverse }}</p>
    
    

Format: format output;

    <p>{{ '%s is %d' | format('name',17) }}</p>
    
    

striptags: delete all HTML tags in the value before rendering;

    <p>{{ '<em>hello</em>' | striptags }}</p>
    
    

Statement block filtering (not commonly used):

    {% filter upper %}
      this is a Flask Jinja2 introduction
    {% endfilter %}
    
    

Custom filter:

Add of application object through Flask_ template_ Filter method, the first parameter of the function is the filter function, and the second parameter is the filter name. Then, you can use custom filters in the template.

    def filter_double_sort(ls):
      return ls[::2]
    app.add_template_filter(filter_double_sort,'double_2')
    
    

Web form:

Web form is the basic function of web application.

It is the part responsible for data collection in HTML pages. The form consists of three parts: form label, form field and form button. The form allows users to input data, is responsible for collecting HTML page data, and submits the user input data to the server through the form.

In Flask, in order to process web forms, we usually use the Flask WTF extension, which encapsulates WTForms and has the function of verifying form data.

HTML standard fields supported by WTForms

WTForms common validation functions

The parameter secret needs to be configured to use flask WTF_ KEY.

CSRF_ENABLED is for CSRF (Cross Station Request Forgery) protection.
SECRET_KEY is used to generate encryption token. When CSRF is activated, this setting will generate encryption token according to the set key.

    <form method='post'>
      <input type="text" name="username" placeholder='Username'>
      <input type="password" name="password" placeholder='password'>
      <input type="submit">
    </form>
    
    
    from flask import Flask,render_template
    @app.route('/login',methods=['GET','POST'])
    def login():
      if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print username,password
      return render_template('login.html',method=request.method)
    
    

Configuration parameters:

    app.config['SECRET_KEY'] = 'silents is gold'
    {{ form.username.label }}
    {{ form.username() }}
    {{ form.password.label }}
    {{ form.password() }}
    {{ form.submit() }}
    
    

We use the login page to demonstrate the use of the form.

    #coding=utf-8
    from flask import Flask,render_template,\
      flash,redirect,url_for,session
    #Import Form base class of WTF extension package
    from flask_wtf import Form
    from wtforms.validators import DataRequired,EqualTo
    from wtforms import StringField,PasswordField,SubmitField
    app = Flask(__name__)
    #Set secret_key to prevent cross site request attacks
    app.config['SECRET_KEY'] = '2017'
    #Custom Form class, inheriting Form
    class Login(Form):
      us = StringField(validators=[DataRequired()])
      ps = PasswordField(validators=[DataRequired(),EqualTo('ps2','error')])
      ps2 = PasswordField(validators=[DataRequired()])
      submit = SubmitField()
    #Define view functions, instantiate custom form classes,
    @app.route('/',methods=['GET','POST'])
    def forms():
      #Instantiate form object
      form = Login()
      if form.validate_on_submit():
      #Get form data
        user = form.us.data
        pswd = form.ps.data
        pswd2 = form.ps2.data
        print user,pswd,pswd2
        session['name'] = form.us.data
        flash(u'Login successful')
        return redirect(url_for('forms'))
      else:
        print form.validate_on_submit()
      return render_template('forms.html',form=form)
    if __name__ == "__main__":
      app.run(debug=True)
    
    

Control statement

Several common control statements:

if control statement in template

    @app.route('/user')
    def user():
      user = 'dongGe'
      return render_template('user.html',user=user)
    
    
    <html>
     <head>
       {% if user %}
        <title> hello {{user}} </title>
      {% else %}
         <title> welcome to flask </title>    
      {% endif %}
     </head>
     <body>
       <h1>hello world</h1>
     </body>
     </html>
    
    

for loop statement in template

     @app.route('/loop')
     def loop():
      fruit = ['apple','orange','pear','grape']
      return render_template('loop.html',fruit=fruit)
    
    
     <html>
     <head>
       {% if user %}
        <title> hello {{user}} </title>
      {% else %}
         <title> welcome to flask </title>    
      {% endif %}
     </head>
     <body>
       <h1>hello world</h1>
      <ul>
        {% for index in fruit %}
          <li>{{ index }}</li>
        {% endfor %}
      </ul>
     </body>
     </html>
    
    

Macro:

Similar to functions in python, macros are used to reuse code in templates to avoid code redundancy.

Jinja2 supports macros and can also import macros. Template code fragments that need to be reused in multiple places can be written into a separate file and included in all templates to avoid duplication.

Ding Yihong

    {% macro input() %}
     <input type="text"
         name="username"
         value=""
         size="30"/>
    {% endmacro %}
    
    

Call macro

    {{ input()}}
    #Define macros with parameters
    #Call the macro and pass the parameters
      <input type="password"
          name=""
          value="name"
          size="40"/>
    
    

Template inheritance:

Template inheritance is to reuse the public content in the template. {% block head
%}The elements defined by the tag can be modified in the derived template. The extends instruction declares where the template inherits from? The block defined in the parent template is redefined in the child template, and super() can be used to call the parent template content in the subtemplate.

     {% extends 'base.html' %}
     {% block content %}
      <h1> hi,{{ name }} </h1>
     {% for index in fruit %}
      <p> {{ index }} </p>
     {% endfor %}
     {% endblock %}
    
    

Special variables and methods in Flask:

In Flask, there are some special variables and methods that can be accessed directly in the template file.

config object:

The config object is the config object of Flask, that is, app Config object.

    {{ config.SQLALCHEMY_DATABASE_URI }}
    
    

request object:

It is the request object in Flask that represents the current request.

    {{ request.url }}
    
    

url_for method:

url_for() will return the URL corresponding to the incoming routing function, which is called app route()
The function decorated by the route decorator. If the routing function we define has parameters, these parameters can be passed in as named parameters.

    {{ url_for('index') }}
    {{ url_for('post', post_id=1024) }}
    
    

get_flashed_messages method:

Returns the list of information previously passed in through flash() in flash. Add the message represented by the string object to a message queue, and then call
get_flashed_messages() method.

    {% for message in get_flashed_messages() %}
      {{ message }}
    {% endfor %}
    
    

I hope this article will be helpful to Python Programming Based on flash framework.

Keywords: Python

Added by mallard on Sat, 29 Jan 2022 22:16:46 +0200