Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask how to use Response to serve from a generator from a mongo query

Tags:

python

flask

Say that my function "search()" fetches some content in the mongodb and returns the generator.

My flask view function looks like this

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

But if I do that, I get this error:

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

The generator itself would yield several json values. I could always use the generator to construct a list and return the list, but I would like to avoid doing that.

like image 502
Stupid.Fat.Cat Avatar asked Sep 28 '22 09:09

Stupid.Fat.Cat


1 Answers

There are two problems in your code.

  1. You should be sure that your generator yield string type value each time.
  2. Need to use stream_with_context method, which can be imported from flask

Here is the example:

enter image description here

like image 139
kagb Avatar answered Oct 01 '22 18:10

kagb