10

I am trying to do a very simple thing, build an URL for a get request that contains a port number and some parameters, as it follows http://localhost:8080/read?date=whatever

I have tried several ways without success, it shouldn't be too difficult but i cannot come up with a solution.

I hope someone helps me, it would be greatly appreciated

Thanks in advance

2 Answers 2

12

The previous answer was not to the question you actually asked. Try this:

import urllib

myPort = "8080"
myParameters = { "date" : "whatever", "another_parameters" : "more_whatever" }

myURL = "http://localhost:%s/read?%s" % (myPort, urllib.urlencode(myParameters)) 

Basically, urllib has a function to do what you want, called urlencode. Pass it a dictionary containing the parameter/parameter_value pairs you want, and it will make the proper parameters string you need after the '?' in your url.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, i did try a similar solution to that. The problem is that even though the url is correctly built, i get this error: httplib.InvalidURL: nonnumeric port: '8080/read?initialDate=whatever' Is there any other way to do this using a different library or something? Thanks anyway!
1

Here's a simple generic class that you can (re)use:

import urllib
class URL:
    def __init__(self, host, port=None, path=None, params=None):
        self.host = host
        self.port = port
        self.path = path
        self.params = params

    def __str__(self):
        url = "http://" + self.host
        if self.port is not None:
            url += ":" + self.port
        url += "/"
        if self.path is not None:
            url += self.path
        if self.params is not None:
            url += "?"
            url += urllib.urlencode(self.params)
        return url

So you could do:

url = URL("localhost", "8080", "read", {"date" : "whatever"})
print url

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.