CheeryPy是一个 Pythonic 的、面向对象的 Web 框架,能够用于接受POST或者GET请求并进行回复。
CheeryPy中文文档:
Cherrypy-一个极简的python web框架 — CherryPy 18.6.1.dev44+gc524a0da.d20220502 文档
根据中文文档,给出一个简单的应用例子,
包括:
- import cherrypy
- import json
- import logging
-
- logging.basicConfig(level=logging.DEBUG)
-
- class CheeryPyTest(object):
- @cherrypy.expose # 暴露接口
- def index(self):
- return "Hello world!"
-
- @cherrypy.expose # 暴露接口
- # @cherrypy.tools.json_out()
- @cherrypy.tools.json_in() # 解码JSON请求
- def generate_request(self): # 可以接受GET或者POST请求,参数为key和value
- try:
- request_para = cherrypy.request.json
- if "key" not in request_para or "value" not in request_para:
- logging.error("request para error!, request:%s", str(request_para))
- return "request para error!"
- key = request_para["key"]
- value = request_para["value"]
- logging.info("key: %s, value: %s", key, value)
- return "request succ!"
- except Exception as e:
- logging.error('unknow error: %s', e)
- return "request error!"
-
- def main():
- cherrypy.config.update({'server.socket_host': '0.0.0.0', # 主机IP
- 'server.socket_port': 7090, # 自定义端口
- 'engine.autoreload.on': False})
- cherrypy.quickstart(CheeryPyTest())
-
- if __name__ == '__main__':
- main()
示例包括两个接口
第一个接口:
直接请求 :http://127.0.0.1:8080:7090/index,
正常返回:"hello world"
第二个接口:
通过http://127.0.0.1:8080:7090,加上POST请求参数即可
- {
- "key": "hello",
- "value": "world"
- }
或者使用curl请求的方式:
curl -H "Content-Type: application/json" -X POST -d '{"key": "hello", "value":"world"}' http://localhost:7090/generate_request
主函数
- import cherrypy
-
- def main():
- listening_port = 8080
-
- cherrypy.config.update({'server.socket_port': int(listening_port),
- 'server.socket_host': '0.0.0.0',
- 'engine.autoreload.on': False})
-
- # 这里能够挂载一些服务结束前要执行的函数
- # cherrypy.engine.subscribe('exit', lambda: log.stop()))
- cherrypy.quickstart(None, '/')
-
- if __name__ == '__main__':
- main()
方法函数
- import cherrypy
-
- def api_check_health(environm, start_response):
- """
- api check health
- """
- status = '200 OK'
- response_headers = [('Content-type', 'application/json')]
- start_response(status, response_headers)
- return ['ok']
-
-
-
- # 获取请求参数并处理返回
- def api_get_data(environ, start_response):
- status = '200 OK'
- response_headers = [('Content-type', 'application/json')]
- start_response(status, response_headers)
- request_body_size = int(environ.get('CONTENT_LENGTH', 0))
- request_body = environ['wsgi.input'].read(request_body_size)
-
- rsp = process_func(request_body)
- rsp = rsp.encode("utf-8") # 需要转换
-
- return [rsp]
-
- cherrypy.tree.graft(api_check_health, '/my_server/check_health')
- cherrypy.tree.graft(api_get_data, '/my_server/api_get_data')