Skip to content

Instantly share code, notes, and snippets.

@direct-fuel-injection
Created September 23, 2015 06:54
Show Gist options
  • Save direct-fuel-injection/9c67d234a5ab1fd12c04 to your computer and use it in GitHub Desktop.
Save direct-fuel-injection/9c67d234a5ab1fd12c04 to your computer and use it in GitHub Desktop.
Cherrypy REST API example without MethodDispatcher.
# -*- 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
# -*- 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)
# -*- 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
@ywriterct
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment