Python's `urlparse`: Adding GET keywords to a URL
Asked Answered
T

4

5

I'm doing this:

urlparse.urljoin('http://example.com/mypage', '?name=joe')

And I get this:

'http://example.com/?name=joe'

While I want to get this:

'http://example.com/mypage?name=joe'

What am I doing wrong?

Thermonuclear answered 8/3, 2011 at 12:54 Comment(1)
Why don't you just concatenate them?Slay
T
1

I solved it by bundling Python 2.6's urlparse module with my project. I also had to bundle namedtuple which was defined in collections, since urlparse uses it.

Thermonuclear answered 8/3, 2011 at 16:14 Comment(0)
V
5

You could use urlparse.urlunparse :

import urlparse
parsed = list(urlparse.urlparse('http://example.com/mypage'))
parsed[4] = 'name=joe'
urlparse.urlunparse(parsed)
Vigorous answered 8/3, 2011 at 13:22 Comment(0)
D
1

You're experiencing a known bug which affects Python 2.4-2.6.

If you can't change or patch your version of Python, @jd's solution will work around the issue.

However, if you need a more generic solution that works as a standard urljoin would, you can use a wrapper method which implements the workaround for that specific use case, and default to the standard urljoin() otherwise.

For example:

import urlparse

def myurljoin(base, url, allow_fragments=True):
    if url[0] != "?": 
        return urlparse.urljoin(base, url, allow_fragments)
    if not allow_fragments: 
        url = url.split("#", 1)[0]
    parsed = list(urlparse.urlparse(base))
    parsed[4] = url[1:] # assign params field
    return urlparse.urlunparse(parsed)
Dyson answered 8/3, 2011 at 13:56 Comment(0)
T
1

I solved it by bundling Python 2.6's urlparse module with my project. I also had to bundle namedtuple which was defined in collections, since urlparse uses it.

Thermonuclear answered 8/3, 2011 at 16:14 Comment(0)
P
0

Are you sure? On Python 2.7:

>>> import urlparse
>>> urlparse.urljoin('http://example.com/mypage', '?name=joe')
'http://example.com/mypage?name=joe'
Postbox answered 8/3, 2011 at 12:59 Comment(2)
Damn, it seems to be a Python 2.5 bug! It's fixed in Python 2.6. What can I do? I can't upgrade to 2.6, this is on GAE.Thermonuclear
I can confirm that it works as expected on Python 2.3 but not 2.4.Dyson

© 2022 - 2024 — McMap. All rights reserved.