Discussion on Python using Bottle to provide a simple web service

  • 2020-06-23 00:45:23
  • OfStack

introduce

Today there is a non-trivial requirement to do a quick performance test of restful api, which requires the client to page through the performance of all the jobs in the case of massive job data. Since it was only a small testing effort, the Bottle framework came to mind as an Web server. Here is a brief description of how to use the Bottle framework.

The installation


pip install bottle

Start the service

Run the python script below to start an Web service.


from bottle import route, run, request

@route('/hello')
def hello():
  return "Hello World!"

run(host='0.0.0.0', port=8080, debug=True)

Test, using the following command line to test the service


curl http://localhost:8080/hello

Provide Restful API

The service side

1. Since I need to return some of the results based on parameters (e.g., offset and page size), I can use the dynamic path of Bottle, or I can use parameters.
2. It is assumed that I set the request url as: /jobs//
3. For the convenience of testing, the job information is not returned. Instead, offset and size are returned as json results.

Below is the server-side test code


import json
from bottle import route, run, request

@route('/jobs/<offset:int>/<size:int>')
def get_jobs(offset, size):
  d = {"offset": offset, "size": size}
  return json.dumps(d)

run(host='0.0.0.0', port=8080, debug=True)

The client


import httplib, json

c = httplib.HTTPConnection('localhost', 8080)
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
c.request('GET', '/jobs/123/321', '{}', headers)
s = c.getresponse().read().strip()
print json.loads(s)

conclusion

Above is the whole content of Python using Bottle to provide a simple web service, hoping to be helpful to you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: