无法在python中创建REST服务

2024-04-26 00:38:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个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

有什么办法解决这个问题吗?你知道吗


Tags: runfromimportlocalhosthttpbottleserverplot
1条回答
网友
1楼 · 发布于 2024-04-26 00:38:30

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的目录。重命名/删除该目录,瓶子将从您的网站包目录导入CherryPy。或者您可以简单地从对run()的调用中删除server='cherrypy',以使用默认的wsgiref服务器。你知道吗

相关问题 更多 >