gpt4 book ai didi

Python Flask 如何使用 Response 从 mongo 查询的生成器提供服务

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:33 29 4
gpt4 key购买 nike

假设我的函数“search()”在 mongodb 中获取一些内容并返回生成器。

我的 flask View 函数是这样的

@app.route("search/")
def search_page():
generator = search()
return Response(generator)

但是如果我这样做,我会得到这个错误:

Error on request:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 180, in run_wsgi
execute(self.server.app)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 171, in execute
write(data)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 151, in write
assert type(data) is bytes, 'applications must write bytes'
AssertionError: applications must write bytes

生成器本身会产生几个 json 值。我总是可以使用生成器构建列表并返回列表,但我想避免这样做。

最佳答案

您的代码中有两个问题。

  1. 您应该确保您的生成器每次都生成字符串类型的值。
  2. 需要使用stream_with_context方法,可以从flask中导入

例子如下:

enter image description here

关于Python Flask 如何使用 Response 从 mongo 查询的生成器提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299905/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com