Python Flask how to use Response to feed from a generator from a mongo request

Say my function "search ()" gets some content in mongodb and returns a generator.

My flask view function is as follows

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

But if I do this, 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 will give several json values. I could always use a generator to build a list and return a list, but I would like to avoid this.

+4
source share
2 answers

There are two problems in the code.

  • You must be sure that your generator outputs a string type value each time.
  • You must use the stream_with_context method, which you can import from the flask

Here is an example:

enter image description here

+1
source

- , , . search() - :

bytes = json.dumps(your_content_from_mongo).decode('utf-8')

JSON mongo .

0

All Articles