如何使用 python 请求库发送文件和 json 数据?
How to send file and json data with python requests library?
我正在尝试将带有 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 参数,但效果不佳
感谢@OlvinRoght 我找到了答案。
您可以将数据参数设置为您拥有的任何数据和文件的文件参数。
像这样:
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)
我正在尝试将带有 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 参数,但效果不佳
感谢@OlvinRoght 我找到了答案。
您可以将数据参数设置为您拥有的任何数据和文件的文件参数。
像这样:
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)