python - 无法在 python 中创建 REST 服务

标签 python rest bottle

我想创建一个 REST 服务,所以我尝试了,这是我的代码片段

from bottle import route, run

@route('/plot_graph',method='GET')
def plot_graph():
    #compute graph_list (python object of type list)
    #done
    return graph_list

if __name__ == "__main__":
    run(host='0.0.0.0', port=8881, server='cherrypy', debug=True)

现在当我在浏览器中输入这个 http://localhost:8881/plot_graph它给出了错误

Error: 500 Internal Server Error

Sorry, the requested URL 'http://localhost:8881/plot_graph' caused an error:

Unsupported response type: <type 'int'>

我的 python 控制台说它正在监听,但给出了这个警告

Bottle v0.12.9 server starting up (using CherryPyServer())...
Listening on http://0.0.0.0:8881/
Hit Ctrl-C to quit.

/Users/guru/python_projects/implement_LDA/lda/lib/python2.7/site-packages/bottle.py:2777: ImportWarning: Not importing directory '/Users/guru/python_projects/implement_LDA/lda/cherrypy': missing __init__.py
  from cherrypy import wsgiserver

有什么办法可以解决这个问题吗?

最佳答案

graph_list 需要包含字符串,但是,您的列表似乎包含整数。您可以使用以下命令将这些整数转换为字符串:

return (str(i) for i in graph_list)

但请注意,列表的元素连接在一起,这可能不是您想要的。因此,另一个选择是返回一个字典,bottle 将其转换为 JSON 编码响应:

return {'val{}'.format(i): val for i, val in enumerate(graph_list, 1)}

这将创建一个字典,例如 {'val1': 1, 'val2': 2, 'val3': 2, 'val4': 5}

对于警告问题,您的主 python 脚本所在的目录中似乎有一个名为 cherrypy 的目录。重命名/删除该目录和 Bottle 将从您的 site-packages 目录导入 CherryPy。或者,您可以简单地从对 run() 的调用中删除 server='cherrypy' 以使用默认的 wsgiref 服务器。

关于python - 无法在 python 中创建 REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813465/

相关文章:

python - 手动停止由 mod_wsgi 启动的进程,并监控有多少进程正在运行

python - 尝试在 Apache 后面运行 CherryPy 时出现 403 错误

python - 更改python-pptx中部分文本的字体

java - 在apache http客户端中,如何将StringBody中的Content-Type保持为空或null?

c# - 如果数据库中插入新记录,如何更新 SharePoint Online 列表?

python - 有没有办法在守护进程模式下运行 Bottle 应用程序

python - 在 Python 2.7 中根据正则表达式匹配重新排序列表?

python - 如何填充 kinect v1 深度图像中的黑色补丁

javascript - 如何将图像作为数据放入json中

Python瓶模块导致 "Error: 413 Request Entity Too Large"