Flask framework learning notes

Keywords: Python Back-end Flask


Flask is a lightweight Web application framework written in Python, which can quickly implement a website or Web service using Python language.

1, Introduction

  1. Directory framework (simplest)
    Flask-demo/
    ♪ run.py: application launcher
    ♪ config.py: environment configuration
    ├ static/
    │♪ css /: css file directory
    │♪ img /: picture file directory
    │ └ js /: js file directory
    ♪ templates /: html file directory
    ♪ forms.py: store all forms. If there are many, turn them into one package
    ♪ models.py: store all data models. If there are many, turn them into one package
    └ views.py: store all view functions. If there are many, turn them into a package

  2. test
    (1) Install flash

pip install flask

(2) Testing

from flask import Flask

#The constructor takes the name of the current module (_name _) as a parameter
app = Flask(__name__)

#The route() function is a decorator that tells the application which URL should call the relevant function
#app.route(rule,options) rule: indicates the binding with the url of the function. Options: the parameter list to the rule object
@app.route("/")
def index():
    return "hello,world!"

#app.run(host,port,debug,options)
if __name__ == "__main__":
    app.run(app.run(debug=True,port=5000,host='127.0.0.1'))

Run open web page: http://localhost:5000 You can see the test results

2, Knowledge of Flask

1. Routing

In fact, it is very simple to set a routing address and access it later

@app.route('/index')
def index():
   return 'hello world'

2. Variable rules

You can build URL s dynamically by adding variable parts to rule parameters.

@app.route("/<name>")
def name(name):
    return "hello %s!" % name

When accessing in the browser, enter variables and the page content will change accordingly

visit: http://localhost:/5000/zhangsan
 result: hello zhangsan!

In addition to using strings, you can also use

#Integer variable
@app.route("/<int:postID>")
def int_id(postID):
    return "hello %d!" % postID
#Floating point variable
@app.route("/<float:postID>")
def float_id(postID):
    return "hello %f!" % postID

3. url construction and redirection

url_ The for() function is very useful for dynamically building the URL of a specific function. It accepts the name of the function as the first parameter and one or more keyword parameters, each corresponding to the variable part of the URL.
The Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with the specified status code.
The redirect() function has three parameters: redirect(location, statuscode, response)

  • The location parameter is the URL where the response should be redirected.
  • The statuscode is sent to the browser header. The default is 302.
  • The response parameter is used to instantiate the response.
#Omit some template code!
from flask import Flask,redirect,url_for
@app.route("/<user>")
def index(user):
    return "hello,world!+++%s" % user

@app.route("/<name>")
def name(name):
    return redirect(url_for("index",user=name))

##http://localhost:5000/zhangsan
##hello,world!+++zhangsan

url_ The for() function redirects the program name to the index program, and passes the accepted parameter to the index() function as a user parameter

4.Flask template

jinja2 is a popular template engine for Python. The Web template system combines templates with specific data sources to render dynamic Web pages.

4.1 basic use of formwork

Create a new templates folder under the project to store all template files. Now create a new hello.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Write the page display code here
hello world!
</body>
</html>

Flash file content, don't forget to import the package!!

from flask import Flask,render_template
app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(app.run(debug=True,port=5000,host='127.0.0.1'))

4.2 variable transfer in template

Variables or expressions are modified by {}}, while control statements are modified by {%%}. Other codes are common HTML.
html page (partial)

<body>
Write the page display code here<br>
{{str_data}}<br>
{{int_data}}<br>
{{array_data}}<br>
{{dict_data}}<br>
<br>list Data acquisition method,Obtained by subscript<br>
{{array_data[0]}}
<br>dict Data acquisition method,Obtained by key value pair name<br>
{{dict_data["name"]}}<br>   
{{dict_data.age}}
<br>Simple operations can also be performed<br>
{{array_data[0]+100}}
</body>

Flash page

from flask import Flask,render_template
app = Flask(__name__)

@app.route("/")
def hello():
    #Data to be transferred
    str_data = "hello,world!"
    int_data = 100000
    array_data = [1,2,3,4,5,6]
    dict_data = {"name":'zhangsan',"age":20}
    #render_template: render template
    #Parameter representation: name in template html = data to be transferred in
    return render_template("hello.html",str_data=str_data,int_data=int_data,
                                        array_data=array_data,dict_data=dict_data)

if __name__ == "__main__":
    app.run(app.run(debug=True,port=5000,host='127.0.0.1'))

Operation results:

5. Succession

Last's Jinja2 template supports template inheritance. Personal understanding inheritance is generally applicable to code with a high degree of reusability. For example: navigation bar.
Create a new html in the templates folder

<body>
hello Page inheritance<br>
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br>
<!-- The following is hello Page -->
{% block body %}

{% endblock %}

Modify hello.html in 2

<body>
<!-- Inheritance writing -->
{% extends "layout.html" %}
{% block body %}
    <!-- Write the page display code here<br> -->
    {{str_data}}<br>
    {{int_data}}<br>
    {{array_data}}<br>
    {{dict_data}}<br>
    <br>list Data acquisition method,Obtained by subscript<br>
    {{array_data[0]}}
    <br>dict Data acquisition method,Obtained by key value pair name<br>
    {{dict_data["name"]}}<br>   
    {{dict_data.age}}
    <br>Simple operations can also be performed<br>
    {{array_data[0]+100}}
{% endblock %}
</body>

Run again and you can see

6.Request object

The important attributes of the Request object are listed below:

  • Form: a dictionary object that can get the contents of the post request form
  • args - parses the contents of the query string, which is part of the URL after the question mark (?).
  • Cookies - a dictionary object that holds Cookie names and values.
  • Files - data related to uploaded files.
  • Method: you can GET the current request method, i.e. "GET", "POST", "DELETE", "PUT", etc

example:
The data filled in the form page will trigger '/ result' of the result() function. The result() function collects the form data existing in the request.form in the dictionary object and sends it to result.html.
Flash page

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

#If requested, post will get the contents of the form and transfer the contents to the result page
@app.route("/result",methods=["POST","GET"])
def result():
    if request.method == "POST":
        result = request.form
        return render_template("result.html",result=result)

hello.html form web page code

<body>
    <!-- Clicking submit will deliver the content to the link -->
    <form action="http://localhost:5000/result" method="POST">
        <p>Name <input type = "text" name = "name" /></p>
        <p>age <input type = "text" name = "age" /></p>
        <p><input type = "submit" value = "submit" /></p>
   </form>
</body>

result.html

<!doctype html>
  <table border = 1>
     {% for key, value in result.items() %}
    <tr>
       <th> {{ key }} </th>
       <td> {{ value }}</td>
    </tr>
 {% endfor %}
</table>

result:

https://www.w3cschool.cn/flask/flask_cookies.html
Unfinished

Posted by Rollo Tamasi on Sun, 05 Dec 2021 00:14:49 -0800