Search code examples
pythonrestcherrypy

RESTful web service example in cherrypy


I am trying to write a RESTful web service in python. But while trying out the tutorials given on Cherrypy Website I ended up with an error like

Traceback (most recent call last):
  File "rest.py", line 35, in <module>
    cherrypy.quickstart(StringGeneratorWebService(), '/', conf)
TypeError: expose_() takes exactly 1 argument (0 given)

Where rest.py is my file which contains the exact same code on the site and under subtitle "Give us a REST".

I am clear that, obviously from error message, I am missing a parameter that should be passed in. But I am not clear where exactly I should amend that code to make it work.

I tried out fixing something on line number 35, but nothing helped me, and I am stuck! Please help me to clear this or please give some code snippet to make a REST service in cherrypy. Thank you!


Solution

  • The CherryPy version that you're using (3.2.2) doesn't support the cherrypy.expose decorator on classes, that functionality was added in version 6.

    You can use the old syntax of setting the exposed attribute to True(it is also compatible with the newer versions).

    The class would end up like:

    class StringGeneratorWebService(object):
        exposed = True
    
        @cherrypy.tools.accept(media='text/plain')
        def GET(self):
            return cherrypy.session['mystring']
    
        def POST(self, length=8):
            some_string = ''.join(random.sample(string.hexdigits, int(length)))
            cherrypy.session['mystring'] = some_string
            return some_string
    
        def PUT(self, another_string):
            cherrypy.session['mystring'] = another_string
    
        def DELETE(self):
            cherrypy.session.pop('mystring', None)