This is the 29th day of my participation in Gwen Challenge


The introduction

Flask: A client sends HTTP requests to the Flask application, carrying some information about the request. How do I get it?

from flask import request
Copy the code

The request object is the Flask object that represents the current request. The Request object stores all the data of an HTTP request and encapsulates it. Then we can use the request object to obtain the request information.


Request Common attributes

attribute instructions
data Records requested data, such asJson, XML,
form Record the form data in the request
args Records the query parameters in the request
cookies In the record requestcookieinformation
headers Records the header in the request
method Record the request mode in the request
url Record requestedURLaddress
files Record the file requested for upload


I’m going to use them one by one.

""" Author: hui Desc: {Flask request object usage} ""
from flask import Flask, request

app = Flask(__name__)


@app.route('/')
def hello_world() :
    print('request.data', request.data)
    print('request.url', request.url)
    print('request.method', request.method)
    print('request.headers\n', request.headers)
    print('request.form', request.form)
    print('request.args', request.args)
    print('request.cookies', request.cookies)
    print('request.files', request.files)
    return 'Hello World! '

Copy the code


The PyCharm terminal shows the following results after visiting http://127.0.0.1:5000/

127.0. 01.- -26/Apr/2021 20:21: 03]"The GET/HTTP / 1.1" 200 -
request.data b''

request.url http://127.0. 01.:5000/
        
request.method GET

request.headers
Host: 127.0. 01.:5000
    Connection: keep-alive
    Sec-Ch-Ua: " Not A; Brand"; v="99"."Chromium"; v="90"."Microsoft Edge"; v="90"
    Sec-Ch-Ua-Mobile: ?0
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.04430.72. Safari/537.36 Edg/90.0818.42.Accept: text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,image/apng,*/*; q=0.8,application/signed-exchange; v=b3; q=0.9
    Sec-Fetch-Site: none
    Sec-Fetch-Mode: navigate
    Sec-Fetch-User: ?1Sec-Fetch-Dest: document Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; q=0.9,en; q=0.8,en-GB; q=0.7,en-US; q=0.6
    Cookie: csrftoken=XjZW5a3obvzYxm5dqYtdsWRS5GzVP4tHMJTNquEVJVdWknIJXwRMaTJKYfOTCojh; Hm_lvt_b64a44bf14fabebd68d595c81302642d=1618121686.1618130897.1618133833.1618134629


request.form ImmutableMultiDict([])
request.args ImmutableMultiDict([])
request.cookies ImmutableMultiDict([('csrftoken'.'XjZW5a3obvzYxm5dqYtdsWRS5GzVP4tHMJTNquEVJVdWknIJXwRMaTJKYfOTCojh'), ('Hm_lvt_b64a44bf14fabebd68d595c81302642d'.'1618121686,1618130897,1618133833,1618134629')])
request.files ImmutableMultiDict([])

Copy the code


Get form parameters

So the first thing you’re going to do is you’re going to build the form data, you can either write a web page, or you can use the PostMan tool, and here we’re testing it with PostMan

PostMan tools download website www.postman.com/downloads/

PostMan tool use tutorial can refer to the article PostMan use details


PostMan builds requests and data


Writing view functions

from flask import Flask, request

app = Flask(__name__)

Get form parameter data
@app.route('/index', methods=['GET'.'POST'])
def form_data() :

    name = request.form.get('name')
    age = request.form.get('age')

    Get image data
    pic = request.files.get('pic')
    pic.save('./pic.png')

    name_li = request.form.getlist('name')
    res = 'name={}, age={}'.format(name_li, age)

    print('index')
    print(f'name={name}'.f'age={age}')
    print(f'name_list={name_li}')
    return res
Copy the code


PyCharm displays details

The form is used to extract the request body data

Request. form is a dictionary-like object that extracts form-formatted data directly from the request body

The get method can only get the first of multiple parameters with the same name, and the getList method can get all of them.

Get the form file type data directly using request.files.get. Save the file by calling the save() method.


Gets the query string parameter

Writing view functions

from flask import Flask, request

app = Flask(__name__)

Get query string parameter data
# http://127.0.0.1:5000/args? name=hui&age=21
@app.route('/args', methods=['GET'.'POST'])
def args_data() :
    name = request.args.get('name')
    age = request.args.get('age')
    res = f'name={name}, age={age}'
    print(res)
    return f'<h1> {res} </h1>'
Copy the code


PyCharm Information displayed on the terminal

name=hui, age=21
127.0. 01.- -26/Apr/2021 21:33:55] "GET /args? Name = hui&age = 21 HTTP / 1.1" 200 -
Copy the code


Get data in other formats

Get data such as JSON and XML sent from the front end


Writing view functions

from flask import Flask, request

app = Flask(__name__)

Get data that is not in form format, such as JSON, XML, etc
@app.route('/info', methods=['GET'.'POST'])
def raw_data() :
    If the request body data is not in form format (e.g. Json format), it can be retrieved from request.data
    res = request.data
    return res
Copy the code


The PostMan construct requests a view


Request object knowledge extension

We use the same Request object in each view function as if it were a global variable. In fact, request cannot be a global variable. Imagine a multi-threaded server with multiple threads processing different requests from different clients at the same time. Each thread must see a different request object.

Whereas Django saves view functions as parameters for each request to differentiate between requests, Flask uses context to make certain variables globally accessible in one thread without disturbing other threads.

To get a sense of the concept of Thread Local, see how it works

ThreadLocal{
    "Thread A": {
        args: {'name': 'hui'.'age': 21},
        data: "{"name":"hui","age":"21"}".# assume a JSON string
        form: {'name': 'hui'.'age': 21}... Other data},"Thread B": {
        args: {'name': 'jack'.'age': 22},
        data: "{"name":"jack","age":"22"}",
        form: {'name': 'jack'.'age': 22}... Additional data},...... Other threads} request = threadlocale.get ("Thread name")
Copy the code

Flask first has a request context in the view function, which will fetch the request data of the corresponding thread according to which thread is running.


The source code

Source code has been uploaded to Gitee HuiDBK/FlaskBasic – Code Cloud – Open Source China (gitee.com), welcome to visit.

✍ code word is not easy, but also hope you heroes more support :heart:.


The public,

Create a new folder X

Nature took tens of billions of years to create our real world, while programmers took hundreds of years to create a completely different virtual world. We knock out brick by brick with a keyboard and build everything with our brains. People see 1000 as authority. We defend 1024. We are not keyboard warriors, we are just extraordinary builders of ordinary world.