如何将数据传递给 urllib3 POST 请求方法?

Bla*_*der 2 python urllib3 python-2.7 python-requests

我想使用urllib3库来通过库发出 POST 请求,requests因为它具有连接池和重试等功能。但我找不到以下POST请求的替代品。

import requests
result = requests.post("http://myhost:8000/api/v1/edges", json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })
Run Code Online (Sandbox Code Playgroud)

这在requests库中运行良好,但我无法将其转换为urllib3请求。我试过

import json
import urllib3
urllib3.PoolManager().request("POST","http://myhost:8000/api/v1/edges", body=json.dumps(dict(json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })))
Run Code Online (Sandbox Code Playgroud)

问题是jsonPOST请求中使用as 键传递原始 json 数据。

Mar*_*ers 7

您不需要json关键字参数;您正在将您的字典包装在那里的另一本字典中。

您还需要添加一个Content-Type标题,将其设置为application/json

http = urllib3.PoolManager()
data = {'node_id1': "VLTTKeV-ixhcGgq53", 'node_id2': "VLTTKeV-ixhcGgq51", 'type': 1})
r = http.request(
    "POST", "http://myhost:8000/api/v1/edges", 
    body=json.dumps(data),
    headers={'Content-Type': 'application/json'})
Run Code Online (Sandbox Code Playgroud)