Detailed explanation of the request object of Python Flask

This article introduces the Flask request object, a complete HTTP request, including the Request request sent by the client to the server and the Response response sent by the server. In order to facilitate access to request and response message information, the Flask framework provides some built-in objects, Let's talk about Flask's built-in object requests for requests. Friends who need it can refer to it

Must-know Flask request Flask Request object

Data from the client web page is sent to the server as a global request object. In order to process request data, it should be imported from the Flask module.

Important properties of the Request object are listed below:

form − It is a dictionary object containing key and value pairs of form parameters and their values.

args - The content of the parsed query string, which is the part of the URL after the question mark (?).

Cookies - A dictionary object holding cookie names and values.

files - Data related to uploaded files.

method - the current request method

It is also relatively simple to use request, which is to import the request object directly from the flask module:

from flask import request

1

2

3

4

5

6

7

8

9

"""args - 解析查询字符串的内容,它是问号(?)之后的URL的⼀部分。"""

@app.route('/login', methods=['POST', 'GET'])

 def login():

      if request.method == 'POST':

            user = request.form['nm']

            return redirect(url_for('do_welocome',name = user))

       else:

       user = request.args.get("nm")

       return redirect(url_for('do_welocome',name = user))

You must know that Flask's Cookies obtain data Cookies are stored on the client's computer in the form of text files.

Its purpose is to remember and track data related to customer usage for better visitor experience and website statistics.

Flask's Request object contains Cookie properties.

It is a dictionary object of all cookie variables and their corresponding values

Among other things, the cookie stores its expiry time, path and domain name of the website.

In Flask, the processing steps for cookies are:

1 set cookies:

Set a cookie, the default validity period is a temporary cookie, and it will be invalid when the browser is closed

You can set the validity period through max_age, and the unit is seconds

2 get cookies

To get cookies, through request.cookies, a dictionary is returned, and the corresponding values ​​in the dictionary can be obtained

3 delete cookies

The deletion here is just to expire the cookie, not to delete the cookie directly

To delete a cookie, use delete_cookie(), which contains the name of the cookie

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from flask import  Flask,request,render_template,make_response

app = Flask(__name__)

@app.route('/setcookies')

def set_cookie():

    rep = make_response('设置cookies成功cookie:zhen guo:33')

    rep.set_cookie("zhen guo", '33',max_age = 3600)

    return rep

@app.route('/getcookie')

def get_cookie():

    cookie_value = request.cookies.get('zhen guo')

    return cookie_value

@app.route('/del_cookie')

def del_cookie():

    rep = make_response('删除cookie成功')

    rep.delete_cookie('zhen guo')

    return rep

if __name__ == "__main__":

    app.debug = True

    app.run('127.0.0.1',5000)

Flask file uploads Handling file uploads in Flask is very simple.

All that is required is an HTML form with the enctype attribute set to 'multipart/form-data' to post the file to a URL.

The URL handler extracts the files from the request.files[] object and saves them to the desired location

1

2

3

4

5

6

7

8

9

10

11

12

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<form action="http://127.0.0.1:5000/uploader" method="POST" enctype="multipart/form-data">

<p><input type="file" name="file1" accept=".jpg,.png,.xlsx,.xls"/></p>

<p><input type="submit"/></p> </form>

</body>

</html>

Each uploaded file is first saved in a temporary location on the server

Then actually save it to its Y end position.

The name of the target file can be hardcoded

It can also be obtained from the filename attribute of the request.files[file] object.

However, it is recommended to use the secure_filename() function to get a secure version of it

The path of the default upload folder and the Y value of the uploaded file are defined in the configuration settings of the Flask object

app.config['UPLOAD_FOLDERʼ] defines the path of the upload folder

app.config['MAX_CONTENT_LENGTHʼ] specifies the Y maximum value (in bytes) of the file to be uploaded

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from flask import  Flask,request,render_template,make_response

from werkzeug.utils import secure_filename

import os

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = r'D:\pythonProject1\static'

@app.route('/')

def index():

    return render_template('upload.html')

@app.route('/uploader',methods=['POST','GET'])

def upload():

    if request.method == "POST":

        f = request.files['file1']

        filename = secure_filename(f.filename)

        f.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))

        return f'文件{filename}上传成功'

if __name__ == "__main__":

    app.debug = True

    app.run('127.0.0.1', 5000)

This is the end of this article about the detailed use of Python Flask's request object.

Click to get
50G+ learning video tutorials
100+Python elementary, intermediate and advanced e-books

Guess you like

Origin blog.csdn.net/ai520wangzha/article/details/131046894