req.py
branchstable
changeset 4891 90203ec7b3e3
parent 4466 8b0ca7904820
child 4892 7ee8f128be9e
--- 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