[Master the learning notes of flash framework in one week] Template Html page preparation

Jinja2 template engine

Template

In the previous example, the main function of the view function is to generate the response to 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 code complexity 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
  • Replacing variables with real values and returning the resulting string is called rendering
  • Flask uses Jinja2 as a template engine to render templates

Benefits of using templates:

  • The view function is only responsible for business logic and data processing (business logic)
  • The template takes the data results of the view function for display (view display)
  • Clear code structure and low coupling

Jinja2

Two concepts

Jinja2: it is the next widely used template engine in Python. It is a template language implemented by python. Its design idea comes from Django's template engine and extends its syntax and a series of powerful functions. It is the built-in template language of Flask.
Template language: a simple text format designed to automatically generate documents. In template language, some variables are generally passed to the template to replace the pre-defined placeholder variable name at the specific position of the template.

Render template function

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, representing the real values corresponding to variables in the template.

use

notes

Use {# #} for annotation

{# This is a comment #}
Variable code block

The {}} syntax is called variable code block
{{ post.title }}
The variable code block in Jinja2 template can be any Python type or object, as long as it can be converted into a string by Python's str() method. For example, an element in a dictionary or list can be displayed in the following way:

{{your_dict['key']}}
{{your_list[0]}}
Control code block

The control code block defined with {%%} can realize some language level functions, such as loops or if statements

{% if user %}
    {{ user }}
{% else %}
    hello!
    
{% for index in indexs %}
    {{ index }} 
{% endfor %}

filter

The essence of a filter is a function. Sometimes we not only need to output the value of variables, but also need to modify the display of variables, even formatting, operation, etc. some methods in Python cannot be called directly in the template, so the filter is used.

Usage:

The usage of filter is: variable name | filter.

{{variable | filter_name(*args)}}

If no parameters are passed to the filter, the parentheses can be omitted

{{variable | filter_name}}

For example: ` `, the function of this filter is to convert the first letter of the value of variable to uppercase and other letters to lowercase

call chaining

In jinja2, filters can support chained calls. Examples are as follows:

{{ "hello world" | reverse | upper }}

Common built-in filters

String operation

  • safe: disable escape
<p>{{ '<em>hello</em>' | safe }}</p>
  • capitalize: convert the first letter of the variable value to uppercase and the rest to lowercase
<p>{{ 'hello' | capitalize }}</p>
  • lower: converts the value to lowercase
<p>{{ 'HELLO' | lower }}</p>
  • upper: converts the value to uppercase
<p>{{ 'hello' | upper }}</p>
  • title: capitalize the first letter of each word in the value
<p>{{ 'hello' | title }}</p>
  • reverse: String inversion
<p>{{ 'olleh' | reverse }}</p>
  • Format: format output
<p>{{ '%s is %d' | format('name',17) }}</p>
  • striptags: delete all HTML tags from the value before rendering
<p>{{ '<em>hello</em>' | striptags }}</p>
  • truncate: String truncation
<p>{{ 'hello every one' | truncate(9)}}</p>

List operation

  • First: take the first element
<p>{{ [1,2,3,4,5,6] | first }}</p>
  • Last: take the last element
<p>{{ [1,2,3,4,5,6] | last }}</p>
  • Length: gets the length of the list
<p>{{ [1,2,3,4,5,6] | length }}</p>
  • sum: List summation
<p>{{ [1,2,3,4,5,6] | sum }}</p>
  • Sort: sort list
<p>{{ [6,2,3,1,5,4] | sort }}</p>

Statement block filtering

{% filter upper %}
    A pile of words
{% endfilter %}

Web form

Web form is the basic function of web application.

It is the part responsible for data collection in HTML pages. 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 generally use the Flask WTF extension, which encapsulates WTForms and has the function of verifying form data

HTML standard fields supported by WTForms

Field objectexplain
StringFieldText field
TextAreaFieldMultiline text field
PasswordFieldPassword text field
DateFieldText field with the value datetime Date text format
DateTimeFieldText field with the value datetime Datetime text format
IntegerFieldText field with integer value
DecimalFieldText field with a value of decimal Decimal
FloatFieldText field whose value is a floating point number
BooleanFieldCheck boxes with values of True and False
RadioFieldA set of radio boxes
SelectFieldDrop down list
SelectMutipleFieldDrop down list to select multiple values
FileFieldFile upload field
SubmitFieldForm submit button
FormFieldEmbed a form as a field in another form
FieldListA set of fields of a specified type

WTForms common validation functions

Verification functionexplain
DataRequiredMake sure there is data in the field
EqualToComparing the values of two fields is often used to compare two password entries
LengthVerify the length of the input string
NumberRangeVerify that the value entered is within the numeric range
URLVerify URL
AnyOfVerify that the input value is in the optional list
NoneOfVerify that the input value is not in the optional list

The parameter secret needs to be configured to use flask WTF_ KEY.
CSRF_ENABLED is for CSRF (Cross Site 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. Write form directly in HTML page:

Example

Implement the form in a normal way

Write form directly in HTML page:

<form method="post">
    <label>user name:</label><input type="text" name="username"><br>
    <label>password:</label><input type="password" name="password"><br>
    <label>Confirm password:</label><input type="password" name="password2"><br>
    <input type="submit" value="Submit"><br>
    {% for message in get_flashed_messages() %}
        {{ message }}
    {% endfor %}
</form>

Get form data from view function:

from flask import Flask,render_template,request

app.secret_key = 'heima'

@app.route('/', methods=['GET', 'POST'])
def hello_world():

    # 1. Judge whether the request method is post
    if request.method == 'POST':

        # 2. Obtain parameters, verify the integrity of parameters, and flash if there is any problem
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if not all([username, password, password2]):
            flash('params error')

        # 3. Verify password
        elif password != password2:
            flash('password error')

        # 4. Return 'success' if there is no problem
        else:
            print username
            return 'success'

    return render_template('wtf.html')

Implementing forms using flask WTF

Template page:

<form method="post">
    {#set up csrf_token#}
    {{ form.csrf_token() }}
    {{ form.username.label }}{{ form.username }}<br>
    {{ form.password.label }}{{ form.password }}<br>
    {{ form.password2.label }}{{ form.password2 }}<br>
    {{ form.input }}<br>
</form>

View function:

#coding=utf-8
from flask import Flask, render_template, request, flash
#Import the form class of wtf extension
from flask_wtf import FlaskForm
#Fields required to import custom forms
from wtforms import SubmitField,StringField,PasswordField
#Import the form validator provided by the wtf extension
from wtforms.validators import DataRequired,EqualTo
# Solve coding problems
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

app = Flask(__name__)
app.config['SECRET_KEY']='heima'
#Custom form class, including text field, password field and submit button
# You need to customize a form class

class RegisterForm(FlaskForm):
    username = StringField('user name:', validators=[DataRequired()]})
    password = PasswordField('password:', validators=[DataRequired()])
    password2 = PasswordField('Confirm password:', validators=[DataRequired(), EqualTo('password', 'Inconsistent password input')])
    input = SubmitField('Submit')

#Define the root routing view function, generate the form object, obtain the form data, and verify the form data
@app.route('/form', methods=['GET', 'POST'])
def form():
    register_form = RegisterForm()

    if request.method == 'POST':
        # Call validate_ on_ The submit method can execute the logic of all validation functions at one time
        if register_form.validate_on_submit():
            # Entering here means that all logic has been verified successfully
            username = request.form.get('username')
            password = request.form.get('password')
            password2 = request.form.get('password2')
            print username
            return 'success'

        else:
            #message = register_form.errors.get('password2')[0]
            #flash(message)
            flash('Parameter error')

    return render_template('wtf.html', form=register_form)

Keywords: Python Web Development Flask

Added by bluegray on Fri, 31 Dec 2021 18:50:27 +0200