Python 3 flask framework learning notes

Summary: this chapter mainly records the operation of templates, static files and cookies in the Flask framework

Template 1
The main function of the Flask view function is to respond to HTTP requests. When responding to a page, if you escape and splice the page content by string, it may cause unnecessary and unknown errors, so you can use the template engine.

Using the jinga2 template engine, Flask tries to find the HTML file in the templates folder and returns it. It is mainly realized by the following functions:

flask.render_template(template_name_or_list, context)

Parameters:

  • Template name or list: template name
  • context - the parameter to be passed to the template

Simple example:

from flask import Flask
from flask import render_template

app = Flask(__name__)


@app.route('/study/<username>', methods=['GET'])
def sayhello(username):
    return render_template('Hello.html', username=username)


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

Response page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    {% if  username =='admin' %}
    <p>Hello, {{ username }}</p>
    {% else %}
    <p>{{ username }}, Permission denied </p>
    {% endif %}
</body>
</html>

Browser access: http://127.0.0.1:5000/study/wangwu
Output results:

wangwu, Permission denied

Browser access: http://127.0.0.1:5000/study/admin
Output results:

Hello, admin

The Jinja2 template engine escaped from HTML using the following delimiters

  • {%... %}: for statement
  • ... }}: for expressions that can be printed to template output
  • ... #}: for comments not included in template output
  • The... ##: for line statements

2, Static files
Web applications usually need static files, such as js files or css files. Usually these files are provided from the static folder.

Example: (slightly modify the above HTML file)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename = 'hello.css') }}">
</head>
<body>
    {% if  username =='admin' %}
    <p>Hello, {{ username }}</p>
    {% else %}
    <p>{{ username }}, Permission denied </p>
    {% endif %}
</body>
</html>

Create a new file hello.css in the static directory of the project

p{
    font-size: 60px;
    color: blue;
}

After accessing the connection, you can find that the style has been modified. js files are similar to import.

3, Cookie operation
It is the data (usually encrypted) stored on the user's local terminal by some websites for identifying the user's identity and tracking the Session, which is temporarily or permanently saved by the user's client computer

In Flask, cookies are mainly operated through Request objects. The example is as follows:

from flask import Flask
from flask import render_template
from flask import make_response
from flask import request

app = Flask(__name__)


@app.route('/study/<username>', methods=['GET'])
def sayhello(username):
	# Get the flash.wrappers.response object through the make ﹐ response function
    resp = make_response(render_template('Hello.html', username=username))
    # Setting cookie s through Response objects
    resp.set_cookie('username', username)
    return resp


@app.route('/study/cookie')
def getcookie():
	# Obtain the cookies dictionary through the request.cookies function, and then obtain the specified data
    return request.cookies.get('username')


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

Test:
Browser access: http://127.0.0.1:5000/study/admin and http://127.0.0.1:5000/study/cookie
Back to: admin

You can view the cookies in the request header through F12

Published 40 original articles, won praise 31, visited 620000+
Private letter follow

Tags: Permission denied Session

Posted on Tue, 25 Feb 2020 06:19:26 -0500 by gpittingale