【问题标题】:How to send file and json data with python requests library?如何使用 python 请求库发送文件和 json 数据?
【发布时间】:2022-01-19 17:25:19
【问题描述】:

我正在尝试将带有附加到该请求的 json 数据的文件发送到服务器。 我将文件指定为

my_file = open(filename, 'rb')
file = {
        'upload': (
            os.path.basename(filename), my_file ,
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    }

并附上如下数据:

data = {
        'uuidKey': str(user_key),
        'agree-term': False,
        'is_tarh': is_incentive_traffic_zone,
        'description': ''
    }

最后我使用 python 请求库将所有这些放在一起:

headers = {
        'Content-Type': 'multipart/form-data'
    }
result = requests.post("http://127.0.0.1:5000/schedule-payment", files=file,
                        data=json.dumps(data), headers=headers)

将 Content-Type 设置为 application/json 会导致错误。问题是,当您创建表单并以这种方式发送它们时,如何使用 python 请求库将文件和一些类似 json 的数据发送到服务器?

我也尝试在 requests.post 中使用 json 参数,但效果不佳

【问题讨论】:

  • 我将此问题标记为 “由错字引起”,因为解决方案只是删除不必要的 json.dumps() 电话。我不认为这是一个常见的问题,因为无论是在官方文档还是在某种流行的教程中都找不到这样的代码,所以问题似乎是由实验链引起的。

标签: python python-3.x python-requests


【解决方案1】:

感谢@OlvinR​​oght,我找到了答案。

您可以将数据参数设置为您拥有的任何数据以及文件的文件参数。

像这样:

my_file = open(filename, 'rb')
file = {
        'upload': (
            os.path.basename(filename), my_file ,
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    }
data = {
        'uuidKey': str(user_key),
        'agree-term': False,
        'is_tarh': is_incentive_traffic_zone,
        'description': ''
    }

result = requests.post("http://127.0.0.1:5000/schedule-payment", data=data, files=file)

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2014-10-08
    相关资源
    最近更新 更多