Tuesday, 27 January 2015

Python web server using Cherrypy

Recently, I came across a situation where I was supposed to use python to build a web service. At that time, I didn't even know the syntax of python language. Thanks to Cherrypy module, it's very easy and robust.

I will be showing here the code snippet to create a web service (restful api end point)

(I am not giving steps to install python or cherrypy module installation)

Create a file, say, helloworld.py and add below content.

# import cherrypy module
import cherrypy

# class definition
class HelloWorldService(object):
     # this annotation exposes the behavior
    @cherrypy.expose
    # status behavior definition
    def status(self):
        return"OK"

    @cherrypy.expose
    # sayhello behavior with path params

    def sayhello(selfi, *args):
        pathParam = args[0]
        msg = "Hello %s" %(pathParam)
        return msg

# define configuration
if __name__ == '__main__':
    conf = {
          '/' : {
                        'tools.response_headers.on': True,
                        'tools.response_headers.headers': [('Content-Type', 'application/json'), ('Server', '')]
           }
    }

webapp = HelloWorldService()
# starting the server, by default it run on port 8080, we can change this un-comment below line

# cherrypy.config.update({'server.socket_host': '0.0.0.0','server.socket_port': 8090,})
cherrypy.quickstart(webapp, '/', conf)

After this, start the server.
$ python helloworld.py

Once it starts, try accessing below url.
http://localhost:8080/status/
http://localhost:8080/sayhello/sateesh/




No comments:

Post a Comment