Commits

ben...@localhost.nymphormation.net  committed 648b125

full unicode result now

  • Participants
  • Parent commits 29aa408

Comments (0)

Files changed (4)

File restclient/rest.py

     >>> from restclient import Resource
     >>> res = Resource('http://friendpaste.com')
     >>> res.get('/5rOqE9XTz7lccLgZoQS4IP',headers={'Accept': 'application/json'})
-    '{"snippet": "hi!", "title": "", "id": "5rOqE9XTz7lccLgZoQS4IP", "language": "text", "revision": "386233396230"}'
+    u'{"snippet": "hi!", "title": "", "id": "5rOqE9XTz7lccLgZoQS4IP", "language": "text", "revision": "386233396230"}'
     >>> res.get('/5rOqE9XTz7lccLgZoQS4IP',headers={'Accept': 'application/json'}).http_code
     200
 """
     """Exception raised when a request is malformed"""
 
 
-class ResourceResult(str):
+class ResourceResult(unicode):
     """ result returned by `restclient.rest.RestClient`.
     
     you can get result like as string and  status code by result.http_code, 
 
     """
     def __new__(cls, s, http_code, response):
-        self = str.__new__(cls, s)
+        self = unicode.__new__(cls, force_unicode(s))
         self.http_code = http_code
         self.response = response
         return self
 
 
+def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
+    """
+    Similar to smart_unicode, except that lazy instances are resolved to
+    strings, rather than kept as lazy objects.
+
+    If strings_only is True, don't convert (some) non-string-like objects.
+    """
+    if strings_only and isinstance(s, (types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float)):
+        return s
+    try:
+        if not isinstance(s, basestring,):
+            if hasattr(s, '__unicode__'):
+                s = unicode(s)
+            else:
+                try:
+                    s = unicode(str(s), encoding, errors)
+                except UnicodeEncodeError:
+                    if not isinstance(s, Exception):
+                        raise
+                    # If we get to here, the caller has passed in an Exception
+                    # subclass populated with non-ASCII data without special
+                    # handling to display as a string. We need to handle this
+                    # without raising a further exception. We do an
+                    # approximation to what the Exception's standard str()
+                    # output should be.
+                    s = ' '.join([force_unicode(arg, encoding, strings_only,
+                            errors) for arg in s])
+        elif not isinstance(s, unicode):
+            # Note: We use .decode() here, instead of unicode(s, encoding,
+            # errors), so that if s is a SafeString, it ends up being a
+            # SafeUnicode at the end.
+            s = s.decode(encoding, errors)
+    except UnicodeDecodeError, e:
+        raise CouchitUnicodeDecodeError(s, *e.args)
+    return s
 
 class Resource(object):
     """A class that can be instantiated for access to a RESTful resource, 
         >>> xml = res.get('http://pypaste.com/about')
         >>> json = res.get('http://pypaste.com/3XDqQ8G83LlzVWgCeWdwru', headers={'accept': 'application/json'})
         >>> json
-        '{"snippet": "testing API.", "title": "", "id": "3XDqQ8G83LlzVWgCeWdwru", "language": "text", "revision": "363934613139"}'
+        u'{"snippet": "testing API.", "title": "", "id": "3XDqQ8G83LlzVWgCeWdwru", "language": "text", "revision": "363934613139"}'
     """
 
     charset = 'utf-8'

File tests/_server_test.py

 import unittest
 import urlparse
 
+from restclient.transport import smart_str
+
 HOST = socket.getfqdn('127.0.0.1')
 PORT = (os.getpid() % 31000) + 1024
 
         if path == "/":
             extra_headers = [('Content-type', 'text/plain')]
             self._respond(200, extra_headers, "welcome")
+
+        elif path == "/unicode":
+            extra_headers = [('Content-type', 'text/plain')]
+            self._respond(200, extra_headers, u"éàù@")
+
         elif path == "/json":
             content_type = self.headers.get('content-type', 'text/plain')
             if content_type != "application/json":
             content_length = int(self.headers.get('Content-length', '-1'))
             body = self.rfile.read(content_length)
             self._respond(200, extra_headers, body)
+
+        elif path == "/unicode":
+            content_type = self.headers.get('content-type', 'text/plain')
+            extra_headers.append(('Content-type', content_type))
+            content_length = int(self.headers.get('Content-length', '-1'))
+            body = self.rfile.read(content_length)
+            self._respond(200, extra_headers, body)
+
         elif path == "/json":
             content_type = self.headers.get('content-type', 'text/plain')
             if content_type != "application/json":
         for k, v in extra_headers:
             self.send_header(k, v)
         self.end_headers()
-        self.wfile.write(body)
+        self.wfile.write(smart_str(body))
         self.wfile.close()
 
     def finish(self):

File tests/resource_test.py

         self.assert_(result == "welcome")
         self.assert_(result.http_code == 200)
 
+    def testUnicode(self):
+        result = self.res.get('/unicode')
+        self.assert_(result == u"éàù@")
+
     def testGetWithContentType(self):
         result = self.res.get('/json', headers={'Content-Type': 'application/json'})
         self.assert_(result.http_code == 200)
         result = self.res.get('/qint', test=1)
         self.assert_(result.http_code == 200)
 
-
     def testSimplePost(self):
         result = self.res.post(payload="test")
         self.assert_(result=="test")
 
+    def testPostUnicode(self):
+        result = self.res.get('/unicode', payload=u"éàù@")
+        self.assert_(result == u"éàù@")
+
     def testPostWithContentType(self):
         result = self.res.post('/json', payload="test",
                 headers={'Content-Type': 'application/json'})

File tests/transports_test.py

         result = self.res.get()
         self.assert_(result == "welcome")
 
+    def testUnicode(self):
+        result = self.res.get('/unicode')
+        self.assert_(result == u"éàù@")
+
     def testGetWithContentType(self):
         result = self.res.get('/json', headers={'Content-Type': 'application/json'})
         self.assert_(result.http_code == 200)
         result = self.res.post(payload="test")
         self.assert_(result=="test")
 
+    def testPostUnicode(self):
+        result = self.res.get('/unicode', payload=u"éàù@")
+        self.assert_(result == u"éàù@")
+
     def testPostWithContentType(self):
         result = self.res.post('/json', payload="test",
                 headers={'Content-Type': 'application/json'})