0

Since I do my first steps in Python, I try to figure out, how can I do a simple URL call in Python with key=value pairs like:

http://somehost/somecontroller/action?key1=value1&key2=value2

I tried with some things like:

key1 = 'value'
key2 = 10
requests.get("http://somehost/somecontroller/action?key1=" + value + "&key2=" + str(10))

or

data={'key1': 'value', 'key2': str(10)}
requests.get("http://somehost/somecontroller/action", params=data)

(from here)

But this don't work. I also tried it by calling curl with subprocess.Popen() on different ways, but uhm...

I don't want to check the request, the URL call will be enough.

Community
  • 1
  • 1
Rico
  • 17
  • 5
  • 2
    http://stackoverflow.com/questions/22974772/querystring-array-parameters-in-python-using-requests#22975101 – willoller Dec 03 '15 at 23:54
  • Thanks for the link, but I already tried this solution. It don't work for me. – Rico Dec 04 '15 at 00:36
  • 1
    I think you have typo `data = { 'key1': 'value', 'key2': str(10) }`. What error are you getting? How do you know it's not working? – willoller Dec 04 '15 at 00:41
  • Try `data={'key1': 'value', 'key2': '10'}; requests.get("http://127.0.0.1:5000/", params=data)`, the url will be `http://127.0.0.1:5000/?key1=value&key2=10`. – Remi Guan Dec 04 '15 at 00:47
  • There is no error, the url is simply not build for my needs. when I print the request.url it shows only "http://somehost/somecontroller/" in most of the cases. Missing the action and of course, the kay value part. – Rico Dec 04 '15 at 01:02
  • I know, its not working, cause the right url isn't called. There is a cakephp application, which is working fine, when i call the url over browser or curl from bash. – Rico Dec 04 '15 at 01:06

1 Answers1

0

Using the requests library you can use PreparedRequest.prepare_url to encode the parameters to an url, like:

import requests
p = requests.models.PreparedRequest()

data={'key1': 'value', 'key2': str(10)}
p.prepare_url(url='http://somehost.com/somecontroller/action', params=data)

print p.url

In the last print, you should get:

http://somehost.com/somecontroller/action?key2=10&key1=value
memoselyk
  • 3,993
  • 1
  • 17
  • 28