SoFunction
Updated on 2024-11-17

Python requests usage and django backend processing in detail

1、Common Usage of Requests

In addition to the url, requests have parameters params, data and files, which are used to interact with the server backend.

1.1 Submission of queries

Note that get only supports params, not data and files.

(login_url, params={
    "user": user, 
    "password": password, 
})

1.2. Submission of forms

Note that both data and params are supported:

(form_submit_url, data={
    "user": user, 
    "password": password, 
},  params={
    "pool": pool, 
})

1.3. Attach documents at the time of submission:

files = ["", ""]

# Note that file needs to be opened in binary form.
files = [("files", ((file), open(file, "rb")))
         for file in files]

r = (url, files=files, data=data, params=params)

1.4. Maintain status

Use session to maintain state, log in, then submit the form:

session = ()
(login_url, params)
(form_submit_url, data)

1.5. Viewing results

The most important are the status_code, reason and content member variables:

r = (url, files=files, data=data, params=params)

if r.status_code != 200:
    print(r.status_code, ) # Print the error message.
else:
    print()  # Server returns results

2、django processing

2.1. params incoming parameters

For parameters passed in by requests via params, they can be obtained by getting:

def handler(request):
    return ["pool"]       # If no parameters are passed, an exception is thrown
    # return ("pool") # None when not passed this parameter
    # return ("pool", "abc") # defaults to abc

2.2. data incoming parameters

For parameters passed in by requests via data, they can be obtained by getting:

def handler(request):
    return ["user"]       # If no parameters are passed, an exception is thrown
    # return ("user") # None when not passed this parameter
    # return ("user", "abc") # defaults to abc

2.3. files incoming parameters

For parameters passed in by requests via files, they can be retrieved:

def handler(request):
    for file in ("files"):
        name = 
        content = ()      # is binary
        open(name, "wb").write(content) # Save to local

summarize

to this article on Python requests usage and django backend processing of the article is introduced to this, more related requests usage and django backend processing of the content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!