Basic part of flash in python framework (3) ------ operation of template

Posted by keith73 on Fri, 01 May 2020 11:01:27 +0200

1.flask specific variables and functions:

Variables: g, session, request, config

Functions: URL for(), get flashed messages(), please pay attention to this function. Remember that it is a function. Don't forget to write brackets!!!!!!!!!

I don't need to talk much nonsense. I'll go straight to the code to experience it:

First, explain a bug. When we set "× - * - coding:utf-8 - * -", but when the data returned to the browser page is Chinese characters, there will be character coding problems, as follows:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)

At this point, you need to add the following lines of code to the. py file of the view function to solve the coding problem:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

# -*- coding:utf-8 -*-
from flask import Flask
from flask import flash,render_template,session,g
# Solve coding problems
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


app = Flask(__name__)
app.secret_key = 'hello'


@app.route('/',methods=["GET","POST"])
def hello_world():
    # flash At the bottom is the flash information session , so you need to set secret_key
    flash("python")
    return g.age

@app.route('/set_session', methods=['GET', 'POST'])
def set_session():
    session["name"] = "wangwu"
    g.age = 18
    return render_template('six_variable.html')

if __name__ == '__main__':
    app.run(debug=True)

 

This is the preceding code:
1.flash:
{% for message in get_flashed_messages() %}
    {{ message }}
{% endfor %}
<br>
2.request:<br>
{{ request.url }} <br>  For example, the path obtained is: http://localhost:5000/get_session
{{ request.url_root }} <br>  The results are as follows: http://localhost:5000/
{{ request.url_rule }} <br>  The results are as follows:/get_session {{ request.url_charset }} <br>The results are as follows: utf-8 3.config:<br> {{ config.root_path }} <br>  Get project and path {{ config.DEBUG }} <br>    Obtain DEBUG Value of pattern   Two ways to get the value in the dictionary of the front page {{ config["SECRET_KEY"] }}<br> 4.session:<br> {{ session.name }} <br> {{ session["name"] }} <br> 5.url_for:<br> {{ url_for("set_session") }}<br> <a href="{{ url_for("hello_world") }}">hello_world</a><br> 6.g:<br> {{ g.age }}

 

































Topics: Python Session ascii codec