【问题标题】:Unable to create REST service in python无法在 python 中创建 REST 服务
【发布时间】:2016-12-13 07:11:19
【问题描述】:

我想创建一个 REST 服务,所以我尝试了,这是我的 sn-p

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

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

【问题讨论】:

  • 我在虚拟环境中做了所有事情

标签: python rest bottle


【解决方案1】:

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 服务器。

【讨论】:

  • graph_list 需要包含字符串,为什么?返回数据类型如何影响 Web 服务?
  • 我的意思是您的解决方案有效,但为什么我不能返回整数列表?
  • Bottle 支持来自您的回调/路由的以下返回:bottlepy.org/docs/dev/tutorial.html#generating-content
  • 因为瓶子希望您的函数返回某些类型,例如一个可迭代的字符串。可能的类型记录在bottlepy.org/docs/dev/tutorial.html#generating-content
  • @mhawke 如何将此字符串列表转换为字典?我面临的问题是我的列表也包含重复值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2018-02-28
  • 2018-01-23
  • 2011-12-21
  • 2018-12-25
  • 2016-05-17
  • 1970-01-01
相关资源
最近更新 更多