将CURL Post转换为Python请求失败

时间:2016-09-26 15:27:43

标签: python curl server python-requests

我无法成功转换并执行curl post命令到python代码。

curl命令

curl -X POST -H "Content-Type:application/json; charset=UTF-8" -d '{"name":joe, "type":22, "summary":"Test"}' http://url

转换代码

import requests
import json 

url="http://url"
data = {"name":joe, "type":22, "summary":"Test"}
headers = {'Content-type': "application/json; charset=utf8"}
response  = requests.post (url, data=json.dumps(data), headers=headers)
print response.text
print response.headers

我没有得到任何响应作为回报,当我从shell手动执行它时工作正常,但是当我执行代码时,没有任何反应,我没有看到错误或任何东西。

2 个答案:

答案 0 :(得分:1)

如果您使用的是最新版本的请求之一: 尝试使用'json'kwarg(无需显式转换为json)而不是'data'kwarg:

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

注意:此外,您可以省略“内容类型”标题。

答案 1 :(得分:1)

如果您的环境中配置了代理,请在会话/请求中定义代理。

例如,使用会话:

my_proxies = {  
'http': 'http://myproxy:8080',  
'https': 'https://myproxy:8080'  
}  

session = requests.Session()  
request = requests.Request('POST', 'http://my.domain.com', data=params_template, headers=req_headers, proxies=my_proxies)  
prepped = session.prepare_request(request)  
response = session.send(prepped)  

见文件:
请求http://docs.python-requests.org/en/master/user/quickstart/
会话http://docs.python-requests.org/en/master/user/advanced/

相关问题