david / django-roa (http://welldev.org/)
Turn your models into remote resources that you can access through Django's ORM. ROA stands for Resource Oriented Architecture.
| commit 43: | 44ca10ae1a49 |
| parent 42: | d8ba020d999f |
| branch: | default |
| tags: | 0.8 |
Getting ready for 0.8 release
20 months ago
django-roa /
restclient
/
rest.py
| r43:44ca10ae1a49 | 379 loc | 12.6 KB | embed / history / annotate / raw / |
|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | # -*- coding: utf-8 -
#
# Copyright (c) 2008 (c) Benoit Chesneau <benoitc@e-engura.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
"""
restclient.rest
~~~~~~~~~~~~~~~
This module provide a common interface for all HTTP equest.
>>> 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"}'
>>> res.get('/5rOqE9XTz7lccLgZoQS4IP',headers={'Accept': 'application/json'}).http_code
200
"""
from urllib import quote, urlencode
from restclient.http import getDefaultHTTPClient, HTTPClient
__all__ = ['Resource', 'RestClient', 'ResourceNotFound', \
'Unauthorized', 'RequestFailed', 'ResourceError',
'ResourceResult']
__docformat__ = 'restructuredtext en'
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(ResourceError):
"""Exception raised when an authorization is required to access to
the resource specified.
"""
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,
including authentication.
It can use pycurl, urllib2, httplib2 or any interface over
`restclient.http.HTTPClient`.
"""
def __init__(self, uri, httpclient=None):
"""Constructor for a `Resource` object.
Resource represent an HTTP resource.
:param uri: str, full uri to the server.
:param httpclient: any http instance of object based on
`restclient.http.HTTPClient`. By default it will use
a client based on `pycurl <http://pycurl.sourceforge.net/>`_ if
installed or urllib2. You could also use
`restclient.http.HTTPLib2HTTPClient`,a client based on
`Httplib2 <http://code.google.com/p/httplib2/>`_ or make your
own depending of the option you need to access to the serve
(authentification, proxy, ....).
"""
self.client = RestClient(httpclient)
self.uri = uri
self.httpclient = httpclient
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.uri)
def clone(self):
"""if you want to add a path to resource uri, you can do:
.. code-block:: python
resr2 = res.clone()
"""
obj = self.__class__(self.uri, http=self.httpclient)
return obj
def __call__(self, path):
"""if you want to add a path to resource uri, you can do:
.. code-block:: python
Resource("/path").get()
"""
return type(self)(make_uri(self.uri, path), http=self.httpclient)
def get(self, path=None, headers=None, **params):
""" HTTP GET
:param path: string additionnal path to the uri
:param headers: dict, optionnal headers that will
be added to HTTP request.
:param params: Optionnal parameterss added to the request.
"""
return self.client.get(self.uri, path=path, headers=headers, **params)
def delete(self, path=None, headers=None, **params):
""" HTTP DELETE
see GET for params description.
"""
return self.client.delete(self.uri, path=path, headers=headers, **params)
def head(self, path=None, headers=None, **params):
""" HTTP HEAD
see GET for params description.
"""
return self.client.head(self.uri, path=path, headers=headers, **params)
def post(self, path=None, payload=None, headers=None, **params):
""" HTTP POST
:payload: string passed to the body of the request
:param path: string additionnal path to the uri
:param headers: dict, optionnal headers that will
be added to HTTP request.
:param params: Optionnal parameterss added to the request
"""
return self.client.post(self.uri, path=path, body=payload, headers=headers, **params)
def put(self, path=None, payload=None, headers=None, **params):
""" HTTP PUT
see POST for params description.
"""
return self.client.put(self.uri, path=path, body=payload, headers=headers, **params)
def update_uri(self, path):
"""
to set a new uri absolute path
"""
self.uri = make_uri(self.uri, path)
class RestClient(object):
"""Basic rest client
>>> res = RestClient()
>>> 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"}'
"""
def __init__(self, httpclient=None):
"""Constructor for a `RestClient` object.
RestClient represent an HTTP client.
:param httpclient: any http instance of object based on
`restclient.http.HTTPClient`. By default it will use
a client based on `pycurl <http://pycurl.sourceforge.net/>`_ if
installed or urllib2. You could also use
`restclient.http.HTTPLib2HTTPClient`,a client based on
`Httplib2 <http://code.google.com/p/httplib2/>`_ or make your
own depending of the option you need to access to the serve
(authentification, proxy, ....).
"""
if httpclient is None:
httpclient = getDefaultHTTPClient()
self.httpclient = httpclient
self.status_code = None
self.response = None
def get(self, uri, path=None, headers=None, **params):
""" HTTP GET
:param uri: str, uri on which you make the request
:param path: string additionnal path to the uri
:param headers: dict, optionnal headers that will
be added to HTTP request.
:param params: Optionnal parameterss added to the request.
"""
return self.make_request('GET', uri, path=path, headers=headers, **params)
def head(self, uri, path=None, headers=None, **params):
""" HTTP HEAD
see GET for params description.
"""
return self.make_request("HEAD", uri, path=path, headers=headers, **params)
def delete(self, uri, path=None, headers=None, **params):
""" HTTP DELETE
see GET for params description.
"""
return self.make_request('DELETE', uri, path=path, headers=headers, **params)
def post(self, uri, path=None, body=None, headers=None, **params):
""" HTTP POST
:param uri: str, uri on which you make the request
:body: string passed to the body of the request
:param path: string additionnal path to the uri
:param headers: dict, optionnal headers that will
be added to HTTP request.
:param params: Optionnal parameterss added to the request
"""
return self.make_request("POST", uri, path=path, body=body, headers=headers, **params)
def put(self, uri, path=None, body=None, headers=None, **params):
""" HTTP PUT
see POST for params description.
"""
return self.make_request('PUT', uri, path=path, body=body, headers=headers, **params)
def make_request(self, method, uri, path=None, body=None, headers=None, **params):
""" Perform HTTP call support GET, HEAD, POST, PUT and DELETE.
Usage example, get friendpaste page :
.. code-block:: python
from restclient import RestClient
client = RestClient()
page = resource.request('GET', 'http://friendpaste.com')
Or get a paste in JSON :
.. code-block:: python
from restclient import RestClient
client = RestClient()
client.make_request('GET', 'http://friendpaste.com/5rOqE9XTz7lccLgZoQS4IP'),
headers={'Accept': 'application/json'})
:param method: str, the HTTP action to be performed:
'GET', 'HEAD', 'POST', 'PUT', or 'DELETE'
:param path: str or list, path to add to the uri
:param data: str or string or any object that could be
converted to JSON.
:param headers: dict, optionnal headers that will
be added to HTTP request.
:param params: Optionnal parameterss added to the request.
:return: str.
"""
headers = headers or {}
resp, data = self.httpclient.request(make_uri(uri, path, **params), method=method,
body=body, headers=headers)
status_code = int(resp.status)
if status_code >= 400:
if type(data) is dict:
error = (data.get('error'), data.get('reason'))
else:
error = data
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)
return ResourceResult(data, status_code, resp)
def make_uri(base, *path, **query):
"""Assemble a uri based on a base, any number of path segments, and query
string parameters.
>>> make_uri('http://example.org/', '/_all_dbs')
'http://example.org/_all_dbs'
"""
if base and base.endswith("/"):
base = base[:-1]
retval = [base]
# build the path
path = '/'.join([''] +
[unicode_quote(s.strip('/')) for s in path
if s is not None])
if path:
retval.append(path)
params = []
for k, v in query.items():
if type(v) in (list, tuple):
params.extend([(name, i) for i in v if i is not None])
elif v is not None:
params.append((k,v))
if params:
retval.extend(['?', unicode_urlencode(params)])
return ''.join(retval)
def unicode_quote(string, safe=''):
if isinstance(string, unicode):
string = string.encode('utf-8')
return quote(string, safe)
def unicode_urlencode(data):
if isinstance(data, dict):
data = data.items()
params = []
for name, value in data:
if isinstance(value, unicode):
value = value.encode('utf-8')
params.append((name, value))
return urlencode(params)
|
