Five, Flask_ template + CRSF

 

1. Jinjia2 template engine

Flask built-in template language, its design ideas from Django template engine, and expanded its range of powerful features and syntax.

Render Template function:

  • Flask provided render_template function encapsulates the template engine

  • render_template first argument is the file name of the template, the latter parameters are key-value pairs, represent the true value of the variable in the corresponding template.

 

2. The basic template to use

  1. Set in the view template rendering function
    @app.route('/')
    def index():
        return render_template('index.html')

     

  2. Created under the project templates folder to hold all of template files, and create a template html file in the directory index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    我的模板html内容
    </body>
    </html>

     

3. The template code blocks

{} {} Represent variable name, which is called the syntax {} {} variable block

 

View code:

@app.route("/")
def index():
    title = "网页标题"
    return render_template("index.html",title=title)

 

Template code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
</body>
</html>

 

Jinja2 template variables Python code blocks may be of any type or an object, as long as it can be converted to the Python str () method can be a string, for example, an element may be displayed in a list or dictionary of the following ways :

{{your_dict['key']}}
{{your_list[0]}}

With { %% } defined control block , the language can achieve some level of functionality, such as loops or if statements

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

{##} using the annotation, annotation content can not be rendered in html

{# {{ name }} #

 

4. The  template-specific variables and functions

You can access some of the Flask in their default template in the built-in functions and objects

4.1 config

You can visit Flask current config object directly from the template:

{{config.SQLALCHEMY_DATABASE_URI}}
sqlite:///database.db

4.2 request

That is, representing the flask request object for the current request:

{{request.url}}
http://127.0.0.1

4.3 session

Flask session object

{{session.new}}
True

 

4.4 g variable

Set the value of the variable g in view of the function name attribute, may then be removed directly in a template

{{ g.name }}

 

4.5 url_for()

url_for based on incoming router function name, returns the corresponding URL routing, always use url_for () in the template can safely modify the URL routing binding, you do not have to worry about the template rendering errors link:

{{url_for('home')}}

If we define a route URL with parameters, you can use them as keyword arguments passed url_for (), Flask will fill them into the final generation of the URL:

{{ url_for('post', post_id=1)}}
/post/1

 

5. Process control

Mainly includes two:

- if/else if /else / endif
- for / endfor

5.1 if statement

Jinja2 syntax with Python if statement in the if statement, the latter a Boolean value or returns a Boolean value will determine which processes the code will be executed:

{%if user.is_logged_in() %}
    <a href='/logout'>Logout</a>
{% else %}
    <a href='/login'>Login</a>
{% endif %}

 

Filter may be used in an if statement:

{% if comments | length > 0 %}
    There are {{ comments | length }} comments
{% else %}
    There are no comments
{% endif %}

5.2 Loops

We can use the loop to iterate in Jinja2 in any list or generator function

{% for post in posts %}
    <div>
        <h1>{{ post.title }}</h1>
        <p>{{ post.text | safe }}</p>
    </div>
{% endfor %}

Loops and if statements can be used in combination to continue functional simulation Python cycle, the following cycle will only render post.text not post None of those:

{% for post in posts if post.text %}
    <div>
        <h1>{{ post.title }}</h1>
        <p>{{ post.text | safe }}</p>
    </div>
{% endfor %}

In a for loop block you can access these special variables:

variable description
loop.index The current number of loop iterations (starting from 1)
loop.index0 The current number of loop iterations (starting from 0)
loop.revindex The number of cycles required to end iteration (starting from 1)
loop.revindex0 The number of cycles required to end iteration (starting from 0)
loop.first If this is the first iteration, to True.
loop.last If this is the last iteration, to True.
loop.length Number in the sequence of the project.
loop.cycle In the sequence of values ​​between a bunch of helper functions. See the following sample program.

 

Inside the loop, you can use a special variable called loop to get some information about the for loop

For example: If we want to know the current element number is iterative, and simulate things to do in Python enumerate function, you can use the index attribute loop variables, such as:

{% for post in posts%}
{{loop.index}}, {{post.title}}
{% endfor %}

Such an outcome would output

1, Post title
2, Second Post

cycle when the function of each cycle, returns to its next element parameters, take the above example can be described:

{% for post in posts%}
{{loop.cycle('odd','even')}} {{post.title}}
{% endfor %}

Outputs such a result:

odd Post Title
even Second Post

 

6. Filter

It is essentially a function of the filter. Sometimes we need more than just the output value of a variable, we also need to modify the display of variables, even formatting, calculation, etc., and in the template is not certain methods in Python called directly, then it uses filters .

6.1 Use

Use:

 

  • Use filters: variable name | filters
    {{variable | filter_name(*args)}}

     

  • If no parameter to the filter, the bracket may be omitted
    {{variable | filter_name }}

     

 

 

 

In Jinja2, the filter can support chained calls, for example:

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

 

6.2 Common built-in filter

String Manipulation

 

  • safe: Disable Escape
    <p>{{ '<em>hello</em>' | safe }}</p>

     

  • capitalize: The first letter of the variable value transfer to uppercase, and the rest to small letter
    <p>{{ 'hello' | capitalize }}</p>

     

  • lower: the value to lower case
    <p>{{ 'HELLO' | lower }}</p>

     

  • upper: the value of the transfer to uppercase
    <p>{{ 'hello' | upper }}</p>

     

  • title: the first letter of each word in value are transferred to uppercase
    <p>{{ 'hello' | title }}</p>

     

  • reverse: reverse a string
    <p>{{ 'olleh' | reverse }}</p>

     

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

     

  • striptags: Before rendering the value of all the HTML tags are deleted
    <p>{{ '<em>hello</em>' | striptags }}</p>

     

  • truncate: string truncation
    <p>{{ 'hello every one' | truncate(9)}}</p>

     

List of operations

 

  • 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: Get a list Length
    <p>{{ [1,2,3,4,5,6] | length }}</p>

     

  • sum: sum list
    <p>{{ [1,2,3,4,5,6] | sum }}</p>

     

  • sort: sort the list
    <p>{{ [6,2,3,1,5,4] | sort }}</p>

     

Statement block filter

% Upper% filter { }
     # paperwork # 
{%}% Endfilter

 

6.3  Custom filter

It is a function of the nature of the filter. When the built-in filter template can not meet the demand, you can custom filters. Custom filters implemented in two ways:

  • One is through the application objects Flask add_template_filter method

  • To implement custom filter through decorators

Important: Custom filter name if the name and built-in filtering high regard, will cover a built-in filter.

 

Requirements: Add a list of reverse filter

 

method one

Custom filters implemented by calling method add_template_filter application instance. The method first parameter is the name of the function, the second parameter is the name of the custom filter:

DEF do_listreverse (li):
     # Create a new list by the original list 
    temp_li = List (li)
     # new list wraparound 
    temp_li.reverse ()
     return temp_li 

app.add_template_filter (do_listreverse, ' lireverse ' )

 

Second way

The decorative device to implement custom filters. Decorator incoming parameter is a custom filter name.

app.template_filter @ ( ' lireverse ' )
 DEF do_listreverse (li):
     # Create a new list by the original list 
    temp_li = List (li)
     # new list wraparound 
    temp_li.reverse ()
     return temp_li

 

 

Using the custom filter in html

<br/> my_array 原内容:{{ my_array }}
<br/> my_array 反转:{{ my_array | lireverse }}

operation result

my_array original content: [3, 4, 2, 1, 7, 9 ] 
my_array reverse: [ 9, 7, 1, 2, 4, 3]

 

 

7. template inheritance

In the template, you may experience the following:

  • A plurality of templates having a content identical top and bottom

  • A plurality of template template code with the same content, but the content is not the same value portion

  • A plurality of templates having a content identical block html

Like this happens, you can use JinJa2 template inheritance to achieve

Template inheritance to reuse the template public content. Web development in general, inherited mainly used in the site's top menu, at the bottom. These contents can be defined in the parent template, child template inherit directly, without the need for repeated writing.

 

  • Tags define content

    {% block top %} {% endblock %}

     

  • Equivalent to dig a hole in the parent template, the template inherit the parent when the child template can be filled.

  • Child template extends directive declares which template from the template inheritance

  • Father defined template block is redefined in sub-template, call the parent template in the sub-template content can use super ()

 

Parent template code:

base.html

%% Top Block { } 
  the top menu 
{ % Top endblock% } 

{ % Block Content% } 
{ % endblock Content% } 

{ %% Block bottom } 
  bottom 
{ %}% endblock bottom

 

Sub-template code:

This declaration extends the instruction template inheritance from which

The extends% { ' base.html ' % } 
{ % Block Content% } 
 needs to be filled content 
{ %} endblock Content%

 

 

Precautions when using a template inheritance:

  1. It does not support multiple inheritance but supports multi-layered inheritance

  2. For ease of reading, use extends in the sub-template, try to write in the first line of the template.

  3. You can not define multiple block tags with the same name in a template file.

  4. When multiple block tags in a page, it is recommended to end a name tag, when multiple nested block, read better.

 

 

8.  resolve CSRF attacks Flask project

flask-wtf and wtforms assembly, similar to assembly django of Forms

pip install flask_wtf

 

With Flask, Flask-wtf csrf extension has a comprehensive protection system for our developers, very simple to use

 

  1. Csrf_token secret_key value of the application provided for encrypting the generated
    # . Encrypt the session time has passed if no configuration settings in the configuration item is as follows: 
    app.secret_key = " # Here you can write random string # "

     

  2. CSRFProtect flask_wtf.csrf introduced in class, initialization, initialization and associated app
    from flask_wtf import CSRFProtect
    CSRFProtect(app)

     

  3. CSRF tokens used in the form
    <form method="post" action="/">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
    </form>

     

 

Guess you like

Origin www.cnblogs.com/yijue-lu/p/10960222.html