Created
May 30, 2010 00:31
-
-
Save shazow/418658 to your computer and use it in GitHub Desktop.
Pylons API base controller
This file contains 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
API_METHOD_MAP = {} | |
def expose_api(name): | |
def decorator(fn): | |
API_METHOD_MAP[name] = fn | |
return fn | |
return decorator | |
class ApiController(BaseController): | |
def _index(self, resp): | |
c.template = None | |
try: | |
method, format, pretty = get_many(request.params, required=['method'], optional=['format', 'pretty']) | |
except KeyError, e: | |
raise APIError("Missing required parameter: %s" % e.args[0]) | |
fn = API_METHOD_MAP.get(method) | |
if not fn: | |
raise APIError("Method does not exist: %s" % method) | |
try: | |
r = fn(self) | |
except KeyError, e: | |
raise APIError("Missing required parameter: %s" % e.args[0]) | |
if format == 'html': | |
if not c.template: | |
raise APIError("Method does not have html formatting: %s" % method) | |
return render(c.template) | |
response.headers['Content-Type'] = 'application/json' | |
resp['result'] = r | |
if pretty: | |
return json.dumps(resp, indent=4, sort_keys=True, cls=model.meta.SchemaEncoder) | |
return json.dumps(resp, cls=model.meta.SchemaEncoder) | |
def index(self): | |
resp = { | |
'status': 'ok', | |
'code': 200, | |
'messages': [], | |
'result': {}, | |
} | |
try: | |
r = self._index(resp) | |
if r: | |
return r | |
except APIError, e: | |
resp['messages'] += [e.message] | |
resp['code'] = e.code | |
resp['status'] = 'error' | |
return json.dumps(resp) | |
class MyApiController(ApiController): | |
@expose_api("foo.my_call") | |
def my_api_call(self): | |
return {'foo': 'bar'} | |
# Now if we route our api... | |
# map.connect('/api', controller='api', action='index') | |
# We should be able to call our api... | |
# /api?method=foo.my_call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment