Обработка входящих запросов Flask

Обработка входящих запросов Flask

Автор: Рамис | Статьи 05 января 2023

Небольшая заметка по обработке входящих запросов во Flask.

Метод запроса

request.method - возвращает метод, используемый в текущем запросе - GET, POST, PUT и т.д.

@app.route("/test", methods=["GET", "POST"])
def test():
    print('method:', request.method)

Запрос:

import requests
requests.get('http://localhost:5000/test')
requests.post('http://localhost:5000/test')

Результат:

method: GET
method: POST

Cookies

request.cookies - возвращает отправленные в запросе cookie в виде словаря с парами ключ, значение.

@app.route("/test2")
def test2():
    cookies = request.cookies
    print(cookies)

    session = request.cookies.get('session')
    print(session)

Запрос:

import requests
cookies = {'session': 'ramas'}
requests.get('http://localhost:5000/test2', cookies=cookies)

Результат:

ImmutableMultiDict([('session', 'ramas')])
ramas

Строка запроса

request.args - возвращает словарь ключ и значение, представляющий аргументы строки запроса.

@app.route("/test3")
def test3():
    args = request.args
    print(args)

    q = request.args.get("q")
    print(q)

Запрос:

import requests
requests.get('http://localhost:5000/test3?name=ramas&site=ramziv.com&q=hello')

Результат:

ImmutableMultiDict([('name', 'ramas'), ('site', 'ramziv.com'), ('q', 'hello')])
hello

Данные формы

@app.route("/test4", methods=["GET", "POST"])
def test4():
    if request.method == "POST":

        req = request.form
        print(req)

        email = request.form.get("login")
        print(email)

        pwd = request.form.get("pwd")
        print(pwd)

Запрос:

import requests
data = {'login':'io@ramziv.com', 'pwd':'1234'}
requests.post('http://localhost:5000/test4', data=data)

Результат:

ImmutableMultiDict([('login', 'io@ramziv.com'), ('pwd', '1234')])
io@ramziv.com
1234

JSON

@app.route("/test5", methods=["POST"])
def test5():
    #Вернет истину, если тело запроса содержит JSON
    if request.is_json:

        json_data = request.get_json()
        print(json_data)

        json_data2 = request.json
        print(json_data2)

        name = request.json.get("name")
        print(name)

    return 'hello'

Запрос:

import requests
json = {"name":"ramas", "message":"hello"}
requests.post('http://localhost:5000/test5', json=json)
Результат:

{'name': 'ramas', 'message': 'hello'}
{'name': 'ramas', 'message': 'hello'}
ramas

Файлы

@app.route("/test6", methods=["GET", "POST"])
def test6():

    content_length = request.content_length
    print(f"Content length: {content_length}")

    content_type = request.content_type
    print(f"Content type: {content_type}")

    mimetype = request.mimetype
    print(mimetype)

    file = request.files
    print(file)

    if request.files.get("image"):
        image = request.files["image"]
        print(f"Filename: {image.filename}")
        print(f"Name: {image.name}")
        print(image)

Запрос:

import requests
files = {'image': open('screenshot.jpg','rb')}
requests.post('http://localhost:5000/test6', files=files)
Результат:

Content length: 23474
Content type: multipart/form-data; boundary=e6e76d385555edfac149e708c5451b08
multipart/form-data
ImmutableMultiDict([('image', <FileStorage: 'screenshot.jpg' (None)>)])
Filename: screenshot.jpg
Name: image
<FileStorage: 'screenshot.jpg' (None)>

Несколько файлов

@app.route("/test7", methods=["GET", "POST"])
def test7():
    files = request.files.getlist("files")
    print(files)

Запрос:

import requests
files = [('files', open('screenshot.jpg', 'rb')),
        ('files', open('file.png', 'rb'))]
requests.post('http://localhost:5000/test7', files=files)

Результат:

[<FileStorage: 'screenshot.jpg' (None)>, <FileStorage: 'file.png' (None)>]

Аргументы

request.view_args - возвращает словарь аргументов, переданных в маршрут.

@app.route("/test8/<foo>/<bar>")
def test8(foo, bar):
    view_args = request.view_args
    print(view_args)

    print(bar)

Запрос:

import requests
requests.get('http://localhost:5000/test8/hello/world')

Результат:

{'foo': 'hello', 'bar': 'world'}
world

Информация URL

@app.route("/test9")
def test9():

    host = request.host
    print(f"host: {host}")

    host_url = request.host_url
    print(f"host_url: {host_url}")

    path = request.path
    print(f"path: {path}")

    full_path = request.full_path
    print(f"full_path: {path}")

    url = request.url
    print(f"url: {url}")

    base_url = request.base_url
    print(f"base_url: {base_url}")

    url_root = request.url_root
    print(f"url_root: {url_root}")

Запрос:

import requests
requests.get('http://localhost:5000/test9?q=Hello')

Результат:

host: localhost:5000
host_url: http://localhost:5000/
path: /test9
full_path: /test9
url: http://localhost:5000/test9?q=Hello
base_url: http://localhost:5000/test9
url_root: http://localhost:5000/

Заголовки и прочее

@app.route("/test10")
def test10():

    headers = request.headers
    print(headers)

    accept_encoding = request.headers.get("Accept-Encoding")
    print('accept_encoding:\n', accept_encoding)

    user_agent = request.user_agent
    print('user_agent:\n', user_agent)

    access_route = request.access_route
    print('access_route:\n', access_route)

    endpoint = request.endpoint
    print('endpoint:\n', endpoint)

    is_multiproc = request.is_multiprocess
    print('is_multiproc:\n', is_multiproc)

    is_multithread = request.is_multithread
    print('is_multithread:\n', is_multithread)

    is_secure = request.is_secure
    print('is_secure:\n', is_secure)

    scheme = request.scheme
    print('scheme:\n', scheme)

    remote_addr = request.remote_addr
    print('remote_addr:\n', remote_addr)

    url_rule = request.url_rule.methods
    print('url_rule:\n', url_rule)

Результат:

Host: localhost:5000
Connection: keep-alive
Cache-Control: max-age=0
Sec-Ch-Ua: "Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54
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: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: ru,en;q=0.9,en-GB;q=0.8,en-US;q=0.7


accept_encoding:
    gzip, deflate, br
user_agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54
access_route:
    ImmutableList(['127.0.0.1'])
endpoint:
    test10
is_multiproc:
    False
is_multithread:
    True
is_secure:
    False
scheme:
    http
remote_addr:
    127.0.0.1
url_rule:
    {'OPTIONS', 'HEAD', 'GET'}

Комментарии

Markdown
Войти