Commits

David Larlet committed aded008

Update py-restclient to 1.0.1

Comments (0)

Files changed (8)

 django-roa changelog
 ====================
 
+Version 0.6, 28 December 2008:
+------------------------------
+
+* Clean up remoteauth application.
+* Update py-restclient to 1.0.1.
+
+
 Version 0.5, 27 December 2008:
 ------------------------------
 

django_roa/db/exceptions.py

 class ROAException(Exception):
     def __init__(self, exception):
         if ROA_DJANGO_ERRORS:
-            self.status_code, self.content = exception.message
+            self.message = exception.message
+            self.status_code = exception.status_code
         else:
             self.message = str(exception)
 
     
     def parse_django_error(self):
         """Extract the summary part of a Django HTML error."""
-        summary = self.content.split('<body>\n<div id="summary">\n  ', 1)[1]\
+        summary = self.message.split('<body>\n<div id="summary">\n  ', 1)[1]\
                               .split('<th>Python Executable:</th>', 1)[0]
         result = []
         title = None

django_roa/db/models.py

 from django.db.models.fields.related import OneToOneRel, ManyToOneRel, OneToOneField
 from django.utils.functional import curry
 
-from restclient.rest import Resource, RequestFailed
+from restclient import Resource, RequestFailed
 from django_roa.db.exceptions import ROAException
 
 class ROAModelBase(ModelBase):

django_roa/db/query.py

 from django.core import serializers
 from django.db.models.sql.constants import LOOKUP_SEP
 
-from restclient.rest import Resource, ResourceNotFound
+from restclient import Resource, ResourceNotFound
 
 
 class Query(object):

docs/overview.rst

 You can easily switch from local storage of data to remote one given a unique
 setting. That's very useful if you need to develop locally.
 
-Python 2.4 or greater and Django 1.O.2 or greater are required.
-Restclient 0.2.1 is included, it will use pycurl, urllib2 or httplib2.
+Python 2.4 and Django 1.O.2 are required (or greater).
+Py-restclient 1.0.1 is included, it will use pycurl, urllib2 or httplib2.
 
 
 Installation

restclient/__init__.py

     __version__ = '?'
 
 
-from restclient.rest import Resource, RestClient
+from restclient.rest import * 
 
 

restclient/http.py

     status = 200
     final_url = None
     
-    def __init__(self, final_url=None, status=None, headers=None):
+    def __init__(self, final_url=None, status=None, headers=None,
+            body=None):
         self.final_url = final_url
         self.status_code = status
         self.headers = headers
+        self.body = body
 
     def __repr__(self):
         return "<%s status %s for %s>" % (self.__class__.__name__,
         resp = HTTPResponse()
         resp.final_url = response.geturl()
         resp.headers = dict(response.info().items())
+        resp.body = response.read()
 
         if hasattr(response, 'code'):
             resp.status = response.code
         else:
             resp.status = 200
 
-        return resp, response.read()
+        return resp, resp.body
 
 class CurlHTTPClient(HTTPClient):
     """
             try:
                 c.perform()
             except pycurl.error, e:
-                raise HTTPError('curl error %s' % e)
+                errno, message = e
+                return self._make_response(final_url=url, status=errno,
+                        body=message)
 
             response_headers = self._parseHeaders(header)
             code = c.getinfo(pycurl.RESPONSE_CODE)
             
-            resp = HTTPResponse()
-            resp.headers = response_headers
-            resp.status = code
-            resp.final_url = url
-
-            return resp, data.getvalue()
+            return self._make_response(final_url=url, status=code,
+                    headers=response_headers, body=data.getvalue())
         finally:
             c.close()
 
+    def _make_response(self, final_url=None, status=None, headers=None,
+            body=None):
+        resp = HTTPResponse()
+        resp.headers = headers
+        resp.status = status
+        resp.final_url = final_url
+        resp.body = body
+        return resp, body 
     
 class HTTPLib2HTTPClient(HTTPClient):
     """An http client that uses httplib2 for performing HTTP
         resp.headers = dict(httplib2_response.items())
         resp.status = int(httplib2_response.status)
         resp.final_url = final_url
+        resp.body = content
 
         return resp, content

restclient/rest.py

     >>> res = Resource('http://friendpaste.com')
     >>> res.get('/5rOqE9XTz7lccLgZoQS4IP',headers={'Accept': 'application/json'})
     '{"snippet": "hi!", "title": "", "id": "5rOqE9XTz7lccLgZoQS4IP", "language": "text", "revision": "386233396230"}'
-
-
+    >>> res.get('/5rOqE9XTz7lccLgZoQS4IP',headers={'Accept': 'application/json'}).http_code
+    200
 """
 from urllib import quote, urlencode
 
 from restclient.http import getDefaultHTTPClient, HTTPClient 
 
 
-__all__ = ['Resource', 'RestClient', 'RestClientFactory', 'ResourceNotFound', \
-        'Unauthorised', 'RequestFailed']
+__all__ = ['Resource', 'RestClient', 'ResourceNotFound', \
+        'Unauthorized', 'RequestFailed', 'ResourceError',
+        'ResourceResult']
 __docformat__ = 'restructuredtext en'
 
 
-class ResourceNotFound(Exception):
-    """Exception raised when a 404 HTTP error is received in response to a
-    request.
+class ResourceError(Exception):
+    def __init__(self, message=None, http_code=None, response=None):
+        self.message = message
+        self.status_code = http_code
+        self.response = response
+
+class ResourceNotFound(ResourceError):
+    """Exception raised when no resource was found at the given url. 
     """
 
-class Unauthorized(Exception):
-    """Exception raised when a 401 HTTP error is received in response to a
-    request.
+class Unauthorized(ResourceError):
+    """Exception raised when an authorization is required to access to
+    the resource specified.
     """
 
-class RequestFailed(Exception):
+class RequestFailed(ResourceError):
     """Exception raised when an unexpected HTTP error is received in response
     to a request.
+    
+
+    The request failed, meaning the remote HTTP server returned a code 
+    other than success, unauthorized, or NotFound.
+
+    The exception message attempts to extract the error
+
+    You can get the status code by e.http_code, or see anything about the 
+    response via e.response. For example, the entire result body (which is 
+    probably an HTML error page) is e.response.body.
     """
 
+class ResourceResult(str):
+    """ result returned by `restclient.rest.RestClient`.
+    
+    you can get result like as string and  status code by result.http_code, 
+    or see anything about the response via result.response. For example, the entire 
+    result body is result.response.body.
+
+    .. code-block:: python
+
+            from restclient import RestClient
+            client = RestClient()
+            page = resource.request('GET', 'http://friendpaste.com')
+            print page
+            print "http code %s" % page.http_code
+
+    """
+    def __new__(cls, s, http_code, response):
+        self = str.__new__(cls, s)
+        self.http_code = http_code
+        self.response = response
+        return self
+
+
 
 class Resource(object):
     """A class that can be instantiated for access to a RESTful resource, 
         
         .. code-block:: python
 
-            Resource("/path").request("GET")
+            Resource("/path").get()
         """
 
         return type(self)(make_uri(self.uri, path), http=self.httpclient)
         """
         return self.client.put(self.uri, path=path, body=payload, headers=headers, **params)
 
-    def get_status_code(self):
-        """ get status code of the last request """
-        return self.client.status_code
-    status_code = property(get_status_code)
 
     def update_uri(self, path):
         """
         resp, data = self.httpclient.request(make_uri(uri, path, **params), method=method,
                 body=body, headers=headers)
 
-        self.status_code = int(resp.status)
-        self.response = resp
+        status_code = int(resp.status)
 
-        if self.status_code >= 400:
+        if status_code >= 400:
             if type(data) is dict:
                 error = (data.get('error'), data.get('reason'))
             else:
                 error = data
 
-            self.error = error
+            if status_code == 404:
+                raise ResourceNotFound(error, http_code=404, response=resp)
+            elif status_code == 401 or status_code == 403:
+                raise Unauthorized(error, http_code=status_code,
+                        response=resp)
+            else:
+                raise RequestFailed(error, http_code=status_code,
+                        response=resp)
 
-            if self.status_code == 404:
-                raise ResourceNotFound(error)
-            elif self.status_code == 401 or self.status_code == 403:
-                raise Unauthorized
-            else:
-                raise RequestFailed((self.status_code, error))
-
-        return data
+        return ResourceResult(data, status_code, resp)
 
 
 def make_uri(base, *path, **query):