Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is python requests packages equivalent to curl --data-urlencode call?

I am using the following command-line call to execute a groovy script on the jenkins CLI server:

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

I am currently working on transforming my bash scripts to python and I want to do the equivalent of the above call with the python requests package (http://docs.python-requests.org/en/master/).

So-far I have

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()

While the command line prints the expected string, the python code does not. It also does not raise an exception.

Also I am not sure if I should use requests.get() or requests.post(). My web-tech knowledge is very limited.

Thank you for your time.

like image 741
Knitschi Avatar asked Dec 12 '17 15:12

Knitschi


2 Answers

Using

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()

works at least for the groovy script in this example and the one that I use in reality. However the urlencode functionality seems to be missing here, so I am not sure if this works for all given groovy scripts.

like image 113
Knitschi Avatar answered Jan 03 '23 13:01

Knitschi


When passing a string in the data parameter, requests posts it without encoding it.

You can either use quote_plus to encode your post data,

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

or split by '&' and '=' to create a dictionary.

scriptData = "script=println 'Hello cruel jenkins-python-groovy world!'"
scriptData = dict(i.split('=') for i in scriptData.split('&'))
like image 35
t.m.adam Avatar answered Jan 03 '23 13:01

t.m.adam