我不熟悉在cherrypy中创建API。所以,我只是制作一个简单的API来添加数字并显示答案。
我用过这个:
import cherrypy
import json
def add(b,c):
return a+b
class addition:
exposed = True
def POST(self,c,d):
result=add(c,d)
return('addition result is' % result)
if __name__=='__main__':
cherrypy.tree.mount(
addition(),'/api/add',
{'/':
{'request.dispatch':cherrypy.dispatch.MethodDispatcher()}
}
)
cherrypy.engine.start()
然后在另一个文件上,为了调用POST方法,我编写了这段代码:
import requests
import json
url = "http://127.0.0.1:8080/api/add/"
data={'c':12,
'd':13
}
payload = json.dumps(data)
headers = {'content-type':"application/json"}
response = requests.request("POST",url,data=payload,headers=headers)
print(response.text)
但是我收到一个错误:HTTPError:(404,'缺少参数:c,d')
我可以知道我哪里出错了。
答案 0 :(得分:0)
首先启动没有JSON以确保您的代码正常工作。然后更新您的代码以使用JSON。这是计算器的一个工作示例。
此示例显示没有JSON。 JSON的示例如下。
服务器端在cherrypy(server1.py
):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cherrypy
def add(a, b):
return a + b
class Calculator:
exposed = True
def POST(self, a, b):
result = add(int(a), int(b))
return 'result is {}'.format(result)
if __name__=='__main__':
app_config = {
'/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()}
}
cherrypy.tree.mount(Calculator(), '/api/add', config=app_config)
cherrypy.config.update({
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 9090,
})
cherrypy.engine.start()
cherrypy.engine.block()
将cherrypy服务器作为单独的进程运行。打开另一个终端窗口,命令行或您使用的任何内容,并使用此API客户端发送请求。将其命名为client1.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
url = 'http://127.0.0.1:9090/api/add'
data = {
'a': 12,
'b': 13
}
response = requests.request('POST', url, data=data)
print(response.text)
如果您发送请求,则会收到此回复:
$ python send.py
result is 25
CherryPy服务器端(server2.py
):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cherrypy
import json
def add(a, b):
return a + b
class Calculator:
exposed = True
@cherrypy.tools.json_in()
def POST(self):
input_json = cherrypy.request.json
result = add(input_json['a'], input_json['b'])
return 'result is {}'.format(result)
if __name__=='__main__':
app_config = {
'/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()}
}
cherrypy.tree.mount(Calculator(), '/api/add', config=app_config)
cherrypy.config.update({
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 9090,
})
cherrypy.engine.start()
cherrypy.engine.block()
API客户端,将其命名为client2.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
url = 'http://127.0.0.1:9090/api/add'
data = {
'a': 12,
'b': 13
}
headers = {'content-type': 'application/json'}
# Note that there is json=data not data=data.
# This automatically converts input data to JSON
r = requests.request('POST', url, json=data, headers=headers)
print(r.status_code)
print(r.text)