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.

6
  • 2
    stackoverflow.com/questions/22974772/… Commented Dec 3, 2015 at 23:54
  • Thanks for the link, but I already tried this solution. It don't work for me. Commented Dec 4, 2015 at 0: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? Commented Dec 4, 2015 at 0: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. Commented Dec 4, 2015 at 0:47
  • There is no error, the url is simply not build for my needs. when I print the request.url it shows only "somehost/somecontroller" in most of the cases. Missing the action and of course, the kay value part. Commented Dec 4, 2015 at 1:02

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.