美文网首页
Python通过requests模块处理form-data请求格

Python通过requests模块处理form-data请求格

作者: Monky | 来源:发表于2020-10-12 14:52 被阅读0次

***** 自用 *****

一、问题:

  1. 接口支持文件上传,但是文件非必须
  2. 按照普通的requests参数进行请求,服务端收到的参数为null

二、解决

  1. 安装 requests_toolbelt 模块,引入该模块下的 MultipartEncoder
  2. 在 请求体 中使用该模块函数,请求头中增加对应参数值

三、安装requests_toolbelt,这个模块在Pycharm中无法直接搜索到,建议通过命令行安装

pip3 install requests_toolbelt

四、示例

from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests


request_body = MultipartEncoder(
    {
        "language": "中文",
        "name": "大魔王",
        "age": "18",
        "height": 180,
        "weight": 180,
        "photo": ""
    }
)

request_header = {
    "Content-Type": request_body.content_type
}

response_body = requests.post("localhost", data=request_body, headers=request_header)

相关文章

网友评论

      本文标题:Python通过requests模块处理form-data请求格

      本文链接:https://www.haomeiwen.com/subject/kwoupktx.html