Python请求类似于我的unix curl脚本

2024-05-31 23:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个unix脚本,它生成一个url并执行它:

export url='http://test.com';
export job_name='MY_JOB_NAME';

jso="{\"parameter\": [{\"name\":\"BRANCH\",\"value\":\"master\"}, {\"name\":\"GITURL\",\"value\":\"https://github.test.com/test/test.git\"}]}";

curl $url/job/$job_name/build --data-urlencode json="$jso";

我想在Python中做完全相同的事情,我尝试使用'requests'和'urllib2'模块,但它们似乎不构成完全相同的请求。在

以下是我尝试过的:

^{pr2}$

我是不是做错了什么?在


Tags: nametest脚本comhttpurlparametervalue
2条回答

试试这个:

params={'BRANCH':'master', 'GITURL':'https://github.test.com/test/test.git'}
resp = requests.post(url, data=payload)

requests:post-a-multipart-encoded-file 不需要将数据转储到json中,因为

Your dictionary of data will automatically be form-encoded when the request is made

我经常使用请求,简单地传递一个dict就可以了。在

如果我们用curl请求访问测试服务器,我们会看到您所做的是发布一个名为json的表单数据字段,其值为JSON编码的字符串。在

~$ curl http://httpbin.org/post  data-urlencode json='{"foo": "bar"}'
{
  "url": "http://httpbin.org/post",
  "json": null,
  "args": {},
  "form": {
    "json": "{\"foo\": \"bar\"}"
  },
  "origin": "0.0.0.0",
  "data": "",
  "headers": {
    "Connection": "close",
    "Content-Type": "application/x-www-form-urlencoded",
    "X-Request-Id": "1b5f0122-9e63-4e58-adff-e59c24f086e5",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.30.0",
    "Content-Length": "35",
    "Accept": "*/*"
  },
  "files": {}
}

尽管如此,我看到的curl脚本和python脚本之间的主要区别是发布的JSON编码数据的结构。在

您的curl脚本将发布以下内容:

^{pr2}$

您的请求代码正在过帐

{
  "name": "BRANCH",
  "value": "foo"
}

所以你没有发布相同的数据。如果您复制并粘贴I的结构并在其上使用json.dumps,那么对request.post的调用应该可以工作。其余部分100%正确。在

相关问题 更多 >