[url] new rebuild_url method on base request stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 12 Mar 2010 14:51:59 +0100
branchstable
changeset 4891 90203ec7b3e3
parent 4890 b54255f82812
child 4892 7ee8f128be9e
[url] new rebuild_url method on base request
req.py
test/unittest_req.py
--- a/req.py	Fri Mar 12 14:50:54 2010 +0100
+++ b/req.py	Fri Mar 12 14:51:59 2010 +0100
@@ -7,9 +7,10 @@
 """
 __docformat__ = "restructuredtext en"
 
+from urlparse import urlsplit, urlunsplit
 from urllib import quote as urlquote, unquote as urlunquote
 from datetime import time, datetime, timedelta
-from cgi import parse_qsl
+from cgi import parse_qs, parse_qsl
 
 from logilab.common.decorators import cached
 from logilab.common.deprecation import deprecated
@@ -270,6 +271,25 @@
             except UnicodeDecodeError: # might occurs on manually typed URLs
                 yield unicode(key, 'iso-8859-1'), unicode(val, 'iso-8859-1')
 
+
+    def rebuild_url(self, url, **newparams):
+        """return the given url with newparams inserted. If any new params
+        is already specified in the url, it's overriden by the new value
+
+        newparams may only be mono-valued.
+        """
+        if isinstance(url, unicode):
+            url = url.encode(self.encoding)
+        schema, netloc, path, query, fragment = urlsplit(url)
+        query = parse_qs(query)
+        # sort for testing predictability
+        for key, val in sorted(newparams.iteritems()):
+            query[key] = (self.url_quote(val),)
+        query = '&'.join(u'%s=%s' % (param, value)
+                         for param, values in query.items()
+                         for value in values)
+        return urlunsplit((schema, netloc, path, query, fragment))
+
     # bound user related methods ###############################################
 
     @cached
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/unittest_req.py	Fri Mar 12 14:51:59 2010 +0100
@@ -0,0 +1,16 @@
+from logilab.common.testlib import TestCase, unittest_main
+from cubicweb.req import RequestSessionBase
+
+class RebuildURLTC(TestCase):
+    def test(self):
+        rebuild_url = RequestSessionBase(None).rebuild_url
+        self.assertEquals(rebuild_url('http://logilab.fr?__message=pouet', __message='hop'),
+                          'http://logilab.fr?__message=hop')
+        self.assertEquals(rebuild_url('http://logilab.fr', __message='hop'),
+                          'http://logilab.fr?__message=hop')
+        self.assertEquals(rebuild_url('http://logilab.fr?vid=index', __message='hop'),
+                          'http://logilab.fr?__message=hop&vid=index')
+
+
+if __name__ == '__main__':
+    unittest_main()