Hackernoon logoCherrypy Introduction: Simple Python Library for Quick Application Development by@vaibhavtyagi

Cherrypy Introduction: Simple Python Library for Quick Application Development

image

For day to day work in dev-ops or for testing team , we need to put stub in between some application to fill the gap for the application which are not present on local testing lab , for that we need to put some stub so that it can mimic like actual application .

We will discuss one tool here which eventually make tester and developer life very easy , The cherrypy library of python.

I will write simplest code example to create HTTP server , which takes json payload in POST request and also send the json response in reply.

Sample request

'http://127.0.0.1:9990/context' 
Payload  '{"tid": "11000098777","deviceid": "9000002020020202"}'

Response from server

{  RESULT : "ACCEPTED"}

Sample code for above requirement in python

Instillation steps

For installing cherrypy you need to use pip utility and can install cherrypy

pip install cherrypy

Server.py

import cherrypy
import os.path
import configparser
import json

class Server(object):
  def __init__(self):
        self.response_json_objectresponse_json_object=''
        with open('./response.json') as f:
            self.response_json_object = json.load(f)

    @cherrypy.expose()
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def context(self):
        return self.response_json_object

configfile=os.path.join(os.path.dirname(__file__),'./server.conf')
cherrypy.quickstart(Server(),'/', config=configfile)
  • Above program is using one config file named server.conf
  • Also it is reading one json file which will be send as json response for the incoming request.

server.conf

[global]
server.socket_host = '127.0.0.1'
server.socket_port = 9990
server.thread_pool=10
tools.staticdir.on = False
tools.staticdir.dir =
log.access_file = "./logs/access1.log"
log.error_file = "./logs/error1.log"
log.screen = False
tools.sessions.on = True

response.json

{  RESULT : "ACCEPTED"}

On Linux terminal you can use below command to run the program

Start the application

paython Server.py &

Test the application

curl -i -X POST -H "Content-Type:application/json" 'http://127.0.0.1:9990/context' --data '{"tid": "11000098777","deviceid": "9000002020020202"}'
{  RESULT : "ACCEPTED"}

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.