Changeset 10491 for main


Ignore:
Timestamp:
13 Aug 2013, 13:14:50 (11 years ago)
Author:
uli
Message:

Add a helper to update URLs query strings correctly.

Location:
main/waeup.cas/trunk/waeup/cas
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • main/waeup.cas/trunk/waeup/cas/server.py

    r10416 r10491  
    55import random
    66import time
     7import urllib
     8from urlparse import urlparse, parse_qsl, urlunparse
    79from webob import exc, Response
    810from webob.dec import wsgify
     
    168170        return open(path, 'r').read()
    169171    return None
     172
     173
     174def update_url(url, params_dict):
     175    """Update query params of an url.
     176
     177    The `url` is modified to have the query parameters set to
     178    keys/values in `params_dict`, preserving any different existing
     179    keys/values and overwriting any existing keys/values that are also
     180    in `params_dict`.
     181
     182    Thus, ``'http://sample?a=1', dict(b='1')`` will result in
     183    ``'http://sample?a=1&b=1`` and similar.
     184    """
     185    parts = [x for x in urlparse(url)]
     186    old_params = dict(parse_qsl(parts[4]))
     187    old_params.update(params_dict)
     188    query_string = urllib.urlencode(old_params)
     189    parts[4] = query_string
     190    return urlunparse(parts)
    170191
    171192
  • main/waeup.cas/trunk/waeup/cas/tests/test_server.py

    r10490 r10491  
    1313    create_tgc_value, check_login_ticket, set_session_cookie,
    1414    check_session_cookie, get_template, delete_session_cookie,
    15     check_service_ticket,
     15    check_service_ticket, update_url
    1616    )
    1717
     
    564564        assert check_service_ticket(
    565565            db,  'ST-123456', 'http://myservice.com', False) is not None
     566
     567    def test_update_url(self):
     568        # we can create valid new urls with query string params updated
     569        url = 'http://sample.com/index?a=1&b=2'
     570        result1 = update_url('http://sample.com/index?a=1&b=2', dict(b='3'))
     571        assert result1 == 'http://sample.com/index?a=1&b=3'
     572        result2 = update_url('http://sample.com/index?b=2', dict(b='3'))
     573        assert result2 == 'http://sample.com/index?b=3'
     574        result3 = update_url('http://sample.com/index', dict(b='3'))
     575        assert result3 == 'http://sample.com/index?b=3'
     576        result4 = update_url('http://sample.com/index?a=2', dict(b='3'))
     577        assert result4 == 'http://sample.com/index?a=2&b=3'
Note: See TracChangeset for help on using the changeset viewer.