Skip to content

Instantly share code, notes, and snippets.

@imbolc
Last active August 29, 2015 14:06
Show Gist options
  • Save imbolc/15576a36d688f5c26e79 to your computer and use it in GitHub Desktop.
Save imbolc/15576a36d688f5c26e79 to your computer and use it in GitHub Desktop.
aiorest (asyncio) class-based resources
import asyncio
import aiorest
import aiohttp
class RESTResource:
# you can redefine it in subclasses
handlers = [
('list', 'GET', []),
('details', 'GET', ['{id}']),
('create', 'POST', []),
('update', 'PUT', ['{id}']),
('delete', 'DELETE', ['{id}']),
]
@classmethod
def register(cls, server, base_url):
instance = cls()
for attr_name, http_method, url_params in cls.handlers:
url = '/'.join([base_url] + url_params)
attr = getattr(instance, attr_name, None)
if attr:
server.add_url(http_method, url, attr)
# --- USAGE ---
class FooResource(RESTResource):
def list(self, request):
return ['foo1', 'foo2']
def details(self, request):
id = request.matchdict['id']
return {'id': id}
server = aiorest.RESTServer(hostname='127.0.0.1')
FooResource.register(server, '/foos')
# --- TEST ---
@asyncio.coroutine
def query():
query = 'GET', 'http://127.0.0.1:8000/foos'
print('\n%s %s' % query)
r = yield from aiohttp.request(*query)
data = yield from r.json()
print('-->', r.status, data)
query = 'GET', 'http://127.0.0.1:8000/foos/1'
print('\n%s %s' % query)
r = yield from aiohttp.request(*query)
data = yield from r.json()
print('-->', r.status, data)
query = 'POST', 'http://127.0.0.1:8000/foos'
print('\n%s %s' % query)
r = yield from aiohttp.request(*query)
data = yield from r.json()
print('-->', r.status, data)
loop = asyncio.get_event_loop()
srv = loop.run_until_complete(loop.create_server(
server.make_handler, '127.0.0.1', 8000))
loop.run_until_complete(query())
GET http://127.0.0.1:8000/foos
--> 200 ['foo1', 'foo2']
GET http://127.0.0.1:8000/foos/1
--> 200 {'id': '1'}
POST http://127.0.0.1:8000/foos
--> 405 {'error_reason': 'Not Allowed', 'error': {'allowed_methods': 'GET'}, 'error_code': 405}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment