CheeryPy是一个 Pythonic 的、面向对象的 Web 框架,能够用于接受POST或者GET请求并进行回复。
CheeryPy中文文档:
Cherrypy-一个极简的python web框架 — CherryPy 18.6.1.dev44+gc524a0da.d20220502 文档
根据中文文档,给出一个简单的应用例子,
包括:
- 接受POST和GET请求,并进行回复
- 解码JSON请求内容
- 通过定义CheeryPy配置文件,自定义请求端口
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)