【问题标题】:What is python requests packages equivalent to curl --data-urlencode call?什么是相当于 curl --data-urlencode 调用的 python 请求包?
【发布时间】:2018-05-26 08:33:14
【问题描述】:

我正在使用以下命令行调用在 jenkins CLI 服务器上执行一个 groovy 脚本:

curl --user 'Knitschi:myPassword' -H "Jenkins-Crumb:1234" --data-urlencode "script=println 'Hello nice jenkins-curl-groovy world!'" localhost:8080/scriptText

我目前正在将我的 bash 脚本转换为 python,我想使用 python requests 包 (http://docs.python-requests.org/en/master/) 执行与上述调用相同的操作。

目前为止

import requests

url = 'http://localhost:8080/scriptText'
myAuth = ('Knitschi', 'myPassword')
crumbHeader = { 'Jenkins-Crumb' : '1234'}
scriptData = "script=println 'Hello cruel jenkins-python-groovy world!'"

response = requests.post(url, auth=myAuth, headers=crumbHeader, data=scriptData)
print(response.text)
response.raise_for_status()

当命令行打印预期的字符串时,python 代码不会。 它也不会引发异常。

我也不确定应该使用requests.get() 还是requests.post()。我的网络技术知识非常有限。

感谢您的宝贵时间。

【问题讨论】:

标签: jenkins python-requests


【解决方案1】:

使用

import requests

url = 'http://localhost:8080/scriptText'
myAuth = ('Knitschi', 'myPassword')
crumbHeader = { 'Jenkins-Crumb' : '1234'}
groovyScript = "println 'Hello cruel jenkins-python-groovy world!'"
scriptData = { "script" : groovyScript}

response = requests.post(url, auth=myAuth, headers=crumbHeader, data=scriptData)
print(response.text)
response.raise_for_status()

至少适用于本示例中的 groovy 脚本和我在现实中使用的脚本。但是这里似乎缺少 urlencode 功能,所以我不确定这是否适用于所有给定的 groovy 脚本。

【讨论】:

    【解决方案2】:

    data 参数中传递字符串时,requests 会在不对其进行编码的情况下发布它。

    您可以使用quote_plus 对您的帖子数据进行编码,

    scriptData = "script=println 'Hello cruel jenkins-python-groovy world!'"
    scriptData = urllib.parse.quote_plus(scriptData, '=')
    

    或用 '&' 和 '=' 分割来创建字典。

    scriptData = "script=println 'Hello cruel jenkins-python-groovy world!'"
    scriptData = dict(i.split('=') for i in scriptData.split('&'))
    

    【讨论】:

    • 感谢您的回答。它不能直接工作,但它给了我一些线索,帮助我找到了至少对我实际的 groovy-script 有效的东西。您的第一个解决方案不起作用。使用它时我得到了 groovy 语法错误,是什么让我认为编码解码的东西是不正确的。
    • 您的第二个解决方案适用于我在示例中使用的简单的 hello-world 脚本,但对于我在实际代码中使用的更复杂的实际脚本却失败了。但是您的回答指出了我的第一个错误。我需要使用scriptData = {'script' : "println 'Hello World'"}而不是`scriptData="script=println 'Hello World'"。我还发现,至少对于我使用的脚本,似乎不需要编码。我可以按原样使用它作为字典中的值,它可以工作。但我不知道这是否适用于任意 groovy 脚本或仅适用于我的情况。
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2013-07-14
    • 2021-07-05
    相关资源
    最近更新 更多