Text/Video streaming didn't work with Blueprint

Hi,
I am trying to stream a modified (added circles) video-stream to the browser.
The "circle-marking" is done via open-cv. The image processing works, but now I want to stream the result to the browser. I used this tutorial:
https://blog.miguelgrinberg.com/post/video-streaming-with-flask

Because it was not working with video I tried to stream text-messages:

	@octoprint.plugin.BlueprintPlugin.route('/stream')
	def streamed_response(self):
		def generate():
			from time import sleep
			yield "1"
			sleep(4)
			yield "2"
			sleep(4)
			yield "3"
		return Response(generate(),mimetype='text/event-stream')

If I call this endpoint via curl I expected 1234, with four second delay between 2 and 3, but instead after eight seconds I received all numbers.
I debugged into tornado.py __call__ and it looks that the body is always a string and not a stream.

Also, I found this stackoverflow-answer: https://stackoverflow.com/questions/23232399/server-sent-events-with-flask-and-tornado/23233100#23233100

It looks like that streaming with a combination with flask and tornado is not possible.

Tornado's WSGIContainer does not support streaming responses from wsgi apps.

I tried to implement my own RequestHandler: tornado.web.RequestHandler, but then I received this error-message:

flask/globals.py", line 20, in _lookup_req_object
    raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context

Has anybody a solution or an idea for this?

thx, in advance
Olli

I found an "ugly" workaround: start an other tornado-server on a different port.

I used this StreamHandler as a tornado.RequestHandler: https://github.com/wildfios/Tornado-mjpeg-streamer-python/blob/482cf358e9af025b9b17dea31f4a8779e6203357/start.py

Now I can stream the modified video-feed to the browser.

To make it a little bit prettier I need to know you can I register a custom RequestHandler to the default tornado-server, instead of starting a new one?
@foosel Do you have an idea or do you know a plugin that used streaming?

Hey I have the solution!

I found your ocotprint-examples: https://github.com/OctoPrint/Plugin-Examples/blob/3439bfb78c04988b5f821e9cabab52ae0b6817e0/add_tornado_route.py

And it's working.

@foosel Thx, for your excellent work!!!

2 Likes