From: Richard Boulton Date: Thu, 16 Jun 2011 12:35:33 +0000 (+0100) Subject: Move the code to encode the request data into a static helper method - I think this... X-Git-Tag: v0.5.0^2~21 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=023ab755e5404fe379a22e0b8536aa668792b71a;p=services%2Fpython-requests.git Move the code to encode the request data into a static helper method - I think this makes the code clearer, but it also prepares the way for reusing the encoding code --- diff --git a/requests/models.py b/requests/models.py index 48ba976..23555b6 100644 --- a/requests/models.py +++ b/requests/models.py @@ -52,16 +52,7 @@ class Request(object): #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``) self.allow_redirects = allow_redirects - if hasattr(data, 'items'): - for (k, v) in data.items(): - self.data.update({ - k.encode('utf-8') if isinstance(k, unicode) else k: - v.encode('utf-8') if isinstance(v, unicode) else v - }) - self._enc_data = urllib.urlencode(self.data) - else: - self._enc_data = self.data = data - + self.data, self._enc_data = self._encode_params(data) #: :class:`Response ` instance, containing #: content and metadata of HTTP Response, once :attr:`sent `. self.response = Response() @@ -204,6 +195,28 @@ class Request(object): self.response = r + @staticmethod + def _encode_params(data): + """Encode parameters in a piece of data. + + If the data supplied is a dictionary, encodes each parameter in it, and + returns the dictionary of encoded parameters, and a urlencoded version + of that. + + Otherwise, assumes the data is already encoded appropriately, and + returns it twice. + + """ + if hasattr(data, 'items'): + result = {} + for (k, v) in data.items(): + result[k.encode('utf-8') if isinstance(k, unicode) else k] \ + = v.encode('utf-8') if isinstance(v, unicode) else v + return result, urllib.urlencode(result) + else: + return data, data + + @staticmethod def _build_url(url, data=None): """Build URLs."""