Login

add port from settings file to an url

Author:
sebnapi
Posted:
June 22, 2012
Language:
Python
Version:
1.4
Tags:
url urlparse port replace-parameters-in-url urlsplit
Score:
0 (after 0 ratings)

I'm working on a Project where on certain places I need absolute URL's, in development mode I need the port 8000 added to any absolute url.

This piece of work, took me some time to figure out. Couldn't find something similiar on the net, it's based on Code from the Python urlparse module.

You can change the "settings.PORT" part to "settings.DEBUG == True" if you like, and so on.

META: replace parameters in URL, edit parameters in URL, edit URL, urlparse

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def with_port(url_str):
    """ Adds to an URL the port from the settings
        useful for development

        >>> with_port("http://localhost/ddd")
        'http://localhost:8000/ddd'
        >>> with_port("localhost/ddd")
        'localhost/ddd'
    """
    try:
        port = settings.PORT
    except AttributeError:
        port = None
    if port == 80:
        port = None
    url_split = urlsplit(url_str)
    if port:
        if not url_split.port and url_split.netloc:
            scheme, netloc, url, query, fragment = url_split
            netloc += ":%s" % port
            url_split = SplitResult(scheme, netloc, url, query, fragment)
    return url_split.geturl()

More like this

  1. Url persistance of GET variables by alex_ndc 6 years, 9 months ago
  2. Url query string template tag (qurl) by pricco 1 year, 11 months ago
  3. Strip trailing .html extensions from URLs so that existing bookmarks work for a legacy site ported to Django by daverowell 8 years, 3 months ago
  4. Add site info to request context by bthomas 6 years, 9 months ago
  5. Remove scheme, host and port from url by twinsant 8 years, 5 months ago

Comments

Please login first before commenting.