session verification and template rendering syntax based on Flask (jinja2)

Catalog

1.http transfer request header parameters

The data in the request header of request.headres shows:

print(type(request.headers))
    """
    Host: 127.0.0.1:5000
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
    Accept-Encoding: gzip, deflate
    Referer: http://127.0.0.1:5000/home
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 26
    Cookie: csrftoken=vDIozqveCEfArdYXlM6goHVlSQEn7h4bDygNphL2Feas60DiM2di0jlqKfxo7xhA
    Connection: keep-alive
    Upgrade-Insecure-Requests: 1
    Cache-Control: max-age=0
    """

2. Processing of request.data parameter in flask

If the request.data cannot be processed, it becomes a string and exists in data

request is processed based on mimetype

Type and string of mimetype: http://www.w3school.com.cn/media/media'mimeref.asp

If the description does not belong to the above type, request will convert the parameter that cannot be processed into Json and store it in data

In fact, we can also get the parameters in request.data and json.loads

Other request parameters:

request.There's no need to remember these methods to get various paths,But know it exists


    # Get the current url path
    print(request.path)# /req
    # The previous path of the current url path
    print(request.script_root) #
    # All paths to the current url
    print(request.url) # http://127.0.0.1:5000/req
    # All paths up to the current url's path
    print(request.url_root ) # http://127.0.0.1:5000/

3. request.json parameter in flask

request.json data when submitting data, you need to specify that the format of the parameter is JSON format

If "application/json" is written in the request and request.json is used, JSON parsing data will be returned, otherwise None will be returned

4. session management in flask

session in flask is the module of flask

session generation mechanism: first create a dictionary, and then form a secret_key + timestamp + Flash built-in signature encryption

  • secret_key: any encryption string can be specified
  • Time stamp: save the expiration time of the session
  • Signature: built in signature, applied to session encryption

Example:

from datetime import timedelta
from flask import Flask, session, request, render_template, redirect

app = Flask(__name__)
# Randomly create a session key
app.secret_key = "#$%^&*#$%^&#$%2213123^&"
# Debug mode
app.debug = True
# Change the name of the session
app.session_cookie_name = "I am Not Session"


# Set the expiration time of the session, 15 seconds
# app.permanent_session_lifetime = 15


@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        uname = request.form.get("username")
        pwd = request.form.get("pwd")

        if uname == "123" and pwd == "123":
            # Set session
            session["username"] = uname
            return "200 OK"
        else:
            return "Login failed!"


@app.route("/detail")
def detail():
    # Verify session settings are successful
    if session.get("username"):
        return render_template("index.html")
    else:
        return redirect("/login")


if __name__ == '__main__':
    app.run("0.0.0.0", 9527)

HTML file:

...
<form action="" method="post" enctype="multipart/form-data">
    User name: < input type = "text" name = "username" >
    Password: < input type = "password" name = "PWD" >
    < input type = "submit" value = "submit" >
</form>
...

5. Template syntax in flask (if,for syntax data processing)

The fallsk template syntax is implemented based on jinja2 syntax

from flask import Flask, render_template

STUDENT = {'name': 'Old', 'age': 38, 'gender': 'in'}

STUDENT_LIST = [
    {'name': 'Old', 'age': 38, 'gender': 'in'},
    {'name': 'Boy', 'age': 73, 'gender': 'male'},
    {'name': 'EDU', 'age': 84, 'gender': 'female'}
]

STUDENT_DICT = {
    1: {'name': 'Old', 'age': 38, 'gender': 'in'},
    2: {'name': 'Boy', 'age': 73, 'gender': 'male'},
    3: {'name': 'EDU', 'age': 84, 'gender': 'female'},
}

app = Flask(__name__)
app.debug = True

@app.route("/index")
def index():
    return render_template("index1.html",
                           stu_info=STUDENT,
                           stu_list=STUDENT_LIST,
                           sd=STUDENT_DICT)


if __name__ == '__main__':
    # Define access ip and port
    app.run("0.0.0.0", 9527)

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# General dictionary data processing #}
{{ stu_info }}
<table border="1ps">
    <tr>
        <td>name</td>
        <td>age</td>
        <td>gender</td>
    </tr>
    <tr>
        <td>{{ stu_info.name }}</td>
        <td>{{ stu_info.age }}</td>
        <td>{{ stu_info.gender }}</td>

    </tr>
</table>
{# Processing of nested dictionary data in list #}
<hr>
{{ stu_list }}
<table border="1ps">
    <tr>
        <td>name</td>
        <td>age</td>
        <td>gender</td>
    </tr>
    {% for foo in stu_list %}
    <tr>
        <td>{{ foo.name }}</td>
        <td>{{ foo.age }}</td>
        {% if foo.gender != "male" and foo.gender != "female" %}
            <td>female</td>
        {% else %}
            <td>{{ foo.gender }}</td>
        {% endif %}
    </tr>
    {% endfor %}
</table>
{# Dictionary data type processing #}
<hr>
{{ sd }}
<table border="1ps">
    <tr>
        <td>name</td>
        <td>age</td>
        <td>gender</td>
    </tr>
    {% for k,v in sd.items() %}
        <tr>
            <td>{{ v.name }}</td>
            <td>{{ v.age }}</td>
            <td>{{ v.gender }}</td>
        </tr>
    {% endfor %}
</table>


</body>
</html>

6. Template syntax in flask (custom function method)

By defining global variables, you can directly use them in the template without importing:

from flask import Flask, render_template  #Decoration customization method

app = Flask(__name__)
app.debug = True


# Custom method, the decorated function here is a global variable
@app.template_global()
def ab(a, b):
    return a + b
@app.template_filter()  # Define global template functions
def a_b_c_sum(a, b, c):
    return a + b + c
@app.route("/index")
def index():
    return render_template("index1.html")


if __name__ == '__main__':
    # Define access ip and port
    app.run("0.0.0.0", 9527)

HTML file: output result 3

...
<body>

<h3>Custom method ab</h3>
//Output result: {ab(1,2)}}
<br>
    {{ 1 | a_b_c_sum(197,2) }}
</body> </html>

7. Template syntax in flask (backend creation label)

7.1 the back end implements the label through the mark up method:

The back end creates a string label, and specifies that the string is a label through Markup, otherwise the front end will display a string

from flask import Flask, render_template, Markup

app = Flask(__name__)
app.debug = True


@app.route("/index")
def index():
    # Mark up label escape, string conversion to label
    my_in = Markup("<input type='text' name='uname'>")
    return render_template("index1.html", m=my_in)


if __name__ == '__main__':
    # Define access ip and port
    app.run("0.0.0.0", 9527)

HTML file:

...
<body>

< HR > create a label from the back-end Code:
Input field: {{m}}

</body>
</html>

7.2 the front end implements the label through the safe ty filter:

from flask import Flask, render_template

app = Flask(__name__)
app.debug = True


@app.route("/index")
def index():
    my_in = "<input type='text' name='uname'>"
    return render_template("index1.html", m=my_in)


if __name__ == '__main__':
    # Define access ip and port
    app.run("0.0.0.0", 9527)

HTML file:

...
<body>

< HR > create a label through the front-end filter:
Input field: {m | safe ty}}}   

</body>
</html>

8. Template syntax in flask (macro method)

from flask import Flask, render_template


app = Flask(__name__)
app.debug = True


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


if __name__ == '__main__':
    # Define access ip and port
    app.run("0.0.0.0", 9527)

HTML file:

mscro implements the creation of tags directly in the front end. At present, it's a little weak and useless

...
<body>

<hr>adopt macro To create a label:
{% macro my_input(na, ny) %}
    <input type="{{ ny }}" name="{{ na }}">
{% endmacro %}

//Input field: {my_input("uname", "type")}}}

</body>
</html>

9.Jinja2 template reuse block

If our front-end page has a large number of duplicate pages, it is not necessary to write them every time. You can reuse the template by reusing the template

Front end code:

Content in index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>The following is different</h2>
    {% block content %}

    {% endblock %}
    <h2>The above content is different,But the following is the same</h2>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Welcome OldboyEDU</h1>
    <h2>The following is different</h2>
    {% block content %}

    {% endblock %}
    <h2>The above content is different,But the following is the same</h2>
    <h1>OldboyEDU is Good</h1>
</body>
</html>

Content in the login.html file

{% extends "index.html" %}
{% block content %}
    <form>
        User name: < input type = "text" name = "user" >
        Password: < input type = "text" name = "PWD" >
    </form>
{% endblock %}
{% extends "index.html" %}
{% block content %}
    <form>
        User name: < input type = "text" name = "user" >
        Password: < input type = "text" name = "PWD" >
    </form>
{% endblock %}

Back end code:

from flask import Flask
from flask import render_template

app = Flask(__name__)


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


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


app.run("0.0.0.0", 5000, debug=True)

10. Module reference include of jinja2 template language

include template syntax: use login.html as a module and load it into the index.html page

Content in the login.html file:

<form>
    User name: < input type = "text" name = "user" >
    Password: < input type = "text" name = "PWD" >
</form>

Content in index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <h2>The following is different</h2>
    {% include "login.html" %}
    <h2>The above content is different,But the following is the same</h2>
</body>
</html>

Back end code:

from flask import Flask
from flask import render_template

app = Flask(__name__)


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


app.run("0.0.0.0", 5000, debug=True)

Keywords: Python Session JSON xml Windows

Added by fgm on Tue, 19 Nov 2019 08:53:52 +0200