天天看点

你确定了解request如何接收数据吗?结果结果结果

转载自:https://zhuanlan.zhihu.com/p/158653107

前后端分离开发是目前web开发最流行的方式之一,本文以python web开发常用框架-flask为例,讲解flask如何使用request来获取前端传输的各种类型数据。

下面,文章针对不同的场景来展示requeset如何处理接收的数据。

二种方式发送请求:

linux: 以CURL来发送API请求

前端:http发送API请求

  1. 参数在url中

    HTTP请求

    POST /test?params=test HTTP/1.1

    Host: 127.0.0.1:5000

    cache-control: no-cache

    CURL请求

    curl -X POST

    'http://127.0.0.1:5000/test?params=test'

    -H 'cache-control: no-cache'

    Python代码

    request.values.get('params')

    request.args.get('params')

  2. token在header中

    HTTP请求

    POST /test HTTP/1.1

    Host: 127.0.0.1:5000

    token: this is a token

    cache-control: no-cache

    CURL请求

    curl -X POST

    http://127.0.0.1:5000/test

    -H 'cache-control: no-cache'

    -H 'token: this is a token'

    Python代码

    request.headers.get('token')

  3. body下的form-data

    HTTP请求

    POST /test HTTP/1.1

    Host: 127.0.0.1:5000

    cache-control: no-cache

    Content-Type: multipart/form-data;

    Content-Disposition: form-data; name="key"

    value

    Content-Disposition: form-data; name="file"; filename="C:\Users\x1c\Desktop\3.jpg

    CURL请求

    curl -X POST

    http://127.0.0.1:5000/test

    -H 'cache-control: no-cache'

    -H 'content-type: multipart/form-data;'

    -F key=value

    -F 'file=@C:\Users\x1c\Desktop\3.jpg'

    Python代码

    request.form.get('key')

    request.files

结果

value

ImmutableMultiDict([('file', <FileStorage: '3.jpg' ('image/jpeg')>)])

4. body下的json

CURL请求

curl -X POST

http://127.0.0.1:5000/test

-H 'Content-Type: application/json'

-H 'cache-control: no-cache'

-d '{"key":"this is a json"}'

HTTP请求

POST /test HTTP/1.1

Host: 127.0.0.1:5000

Content-Type: application/json

cache-control: no-cache

{"key":"this is a json"}

Python代码

request.json

结果

结果