Created
September 23, 2015 06:54
-
-
Save direct-fuel-injection/9c67d234a5ab1fd12c04 to your computer and use it in GitHub Desktop.
Cherrypy REST API example without MethodDispatcher.
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
# -*- coding: utf-8 -*- | |
try: import simplejson as json | |
except ImportError: import json | |
import cherrypy | |
from mapper import Mapper | |
@cherrypy.popargs('songid') | |
class Artists(Mapper): | |
def GET(self, songid, aristid=None): | |
pass | |
def POST(self, songid, model): | |
pass | |
def PUT(self, songid, aristid, model): | |
pass | |
def DELETE(self, songid, aristid): | |
pass |
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
# -*- coding: utf-8 -*- | |
from inspect import getargspec | |
try: import simplejson as json | |
except ImportError: import json | |
import cherrypy | |
from cherrypy import expose | |
__all__ = ['Mapper'] | |
class Mapper(object): | |
@expose | |
def default(self, *args, **kwargs): | |
if len(args) or not hasattr(self, cherrypy.request.method): | |
raise cherrypy.NotFound() | |
http_method = getattr(self, cherrypy.request.method) | |
arg_spec = getargspec(http_method) | |
defaults_count = len(arg_spec.defaults) if arg_spec.defaults else 0 | |
arg_spec_set = set(arg_spec.args[1:len(arg_spec.args)-defaults_count]) | |
arg_method_set = set(kwargs.keys()) | |
# proper 404 error when /api/songs/{{wrong_id}}/artists/35745 | |
if len(arg_spec_set.difference(arg_method_set)): | |
raise cherrypy.NotFound() | |
return (http_method)(*args, **kwargs) |
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
# -*- coding: utf-8 -*- | |
try: import simplejson as json | |
except ImportError: import json | |
import cherrypy | |
from mapper import Mapper | |
from artists import Artists | |
@cherrypy.popargs('songid') | |
class Songs(Mapper): | |
artists = Artists() | |
def GET(self, songid=None): | |
pass | |
def POST(self, model): | |
pass | |
def PUT(self, songid, model): | |
pass | |
def DELETE(self, songid): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi -- i found this through a google search on pop args and method dispatcher, does this work? i'm trying to figure out how to create a REST URIs using cherrypy