繁体   English   中英

Python:从请求库到 urllib3 的转换

[英]Python: conversion from requests library to urllib3

我需要将以下 CURL 命令转换为 Python 中的 http 请求:

curl -X POST https://some/url
-H 'api-key: {api_key}'
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{ "data": { "dirname": "{dirname}", "basename": "{filename}", "contentType": "application/octet-stream" } }'

我最初使用 Python 的请求库成功实现了请求。

import requests

url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...

headers = {
    'api-key': f'{api_key}',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

payload = json.dumps({
    'data': {
        'dirname': f'{dirname}',
        'basename': f'{filename}',
        'contentType': 'application/octet-stream'
    }
})

response = requests.post(url, headers=headers, data=payload)

客户后来要求不要使用pip安装请求库。 为此,我尝试使用 urllib3 库,如下所示:

import urllib3

url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...

headers = {
    'api-key': f'{api_key}',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

payload = json.dumps({
    'data': {
        'dirname': f'{dirname}',
        'basename': f'{filename}',
        'contentType': 'application/octet-stream'
    }
})

http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, body=payload)

问题是现在请求返回一个错误 400,我不明白为什么。

在作为参数传递之前,尝试在payload上调用.encode('utf-8')

或者,尝试将有效负载作为fields传递,而无需手动将其转换为 JSON:

payload = {
  'data': {
    'dirname': f'{dirname}',
    'basename': f'{filename}',
    'contentType': 'application/octet-stream'
  }
}
http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, fields=payload)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM