Created
December 4, 2012 16:46
-
-
Save rcarmo/4206041 to your computer and use it in GitHub Desktop.
api_users.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
import os, sys, logging, json | |
log = logging.getLogger() | |
from bottle import route, get, put, post, delete, request, response, abort | |
import api | |
from models.users import Users | |
prefix = api.prefix + '/users' | |
# Collection URI - List | |
@get(prefix) | |
def list(): | |
page = 25 | |
offset = int(request.query.get('limit','0')) | |
limit = int(request.query.get('limit','25')) | |
# TODO: implement search/query | |
result = {} | |
u = Users() | |
page = u.list(offset,limit) | |
# return keys and URLs for each item | |
for item in page: | |
item['url'] = prefix + '/' + item['id'] | |
# make sure we generate an array | |
result['data'] = [i for i in page] | |
# return pagination helpers | |
if u.count() > limit: | |
result['paging'] = { | |
'next': prefix + '?offset=%d&limit=%d' % (min(len(page),len(page) + offset), limit) | |
} | |
return result | |
# Collection URI - Replace entire collection | |
@put(prefix) | |
def replace(): | |
abort(405,'Not Allowed') | |
# Collection URI - Add item to collection | |
@post(prefix) | |
def append(): | |
abort(501,'Not Implemented') | |
# Collection URI - Delete entire collection | |
@delete(prefix) | |
def remove(): | |
abort(405,'Not Allowed') | |
# Element URI - Retrieve element | |
@get(prefix + '/<id>') | |
def element(id): | |
try: | |
u = Users() | |
return u.get(id) | |
except: | |
abort(404,'Not Found') | |
# Element URI - Replace or create element | |
@put(prefix + '/<id>') | |
def replace(id): | |
# JSON data will be provided in the request body as a single line | |
data = request.body.readline() | |
if not data: | |
abort(400,'No data received') | |
data = json.reads(data) # throws a 500 upon failure | |
# TODO: validate fields | |
try: | |
u = Users() | |
u.put(id, data) | |
except: | |
abort(400,'Could not save %s' % id) | |
# Element URI - Create new named element | |
@post(prefix + '/<id>') | |
def unused(id): | |
abort(501,'Not Implemented') | |
# Element URI - Delete element | |
@delete(prefix + '/<id>') | |
def delete(id): | |
try: | |
u = Users() | |
u.delete(id) | |
abort(200,'OK') | |
except: | |
abort(404,'Not Found') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment