connexion icon indicating copy to clipboard operation
connexion copied to clipboard

Flask Streaming Contents Generator won’t close when clients disconnects.

Open tobiaswer opened this issue 2 years ago • 3 comments

Description

I'm using the FlaskApp and a Flask Streaming Contents Generator to stream a video (image/jpeg) to a client as long as the client is connected. When the client disconnects the Generator won't exit but continue to stream data. Using just Flask without Connexion this works fine. Uvicorn does send out a message = {"type": "http.disconnect"}. Do I miss something in the configuration or is this an issue with the ASGI stack? Thank you!

Expected behaviour

The Generator should exit when the client disconnects.

Actual behaviour

The Generator will continue to generate Data. If the API is called again it will start another Generator and so on.

Steps to reproduce

  1. Start a Response Generator using the FlaskApp.
  2. Connect with a client and disconnect.
  3. The Generator will still continue to run.

Additional info:

Output of the commands:

  • python --version Python 3.10.13

  • pip show connexion | grep "^Version\:" Version: 3.0.3

tobiaswer avatar Dec 01 '23 15:12 tobiaswer

Hi @tobiaswer. Please provide a minimal reproducible example.

RobbeSneyders avatar Dec 02 '23 20:12 RobbeSneyders

app.py

from pathlib import Path
import connexion
import time

def stream():
    def generate():
        count = 0
        try:
            while True:
                time.sleep(1)
                foobar = f"foobar {count}"
                print(foobar)
                yield f"{foobar} <br>"
                count += 1
        except GeneratorExit:
            print('closed')

    return generate()


app = connexion.FlaskApp(__name__, specification_dir="spec/")
app.add_api("openapi.yaml", arguments={"title": "stream Example"})


if __name__ == "__main__":
    app.run(f"{Path(__file__).stem}:app", port=8080)

openapi.yaml

openapi: "3.0.0"

info:
  title: Stream test
  version: "1.0"
servers:
  - url: /openapi

paths:
  /stream:
    get:
      operationId: hello.stream
      responses:
        '200':
          description: stream test
          content:
            text/html: { }

When opening http://127.0.0.1:8080/openapi/stream the server starts streaming and will continue even after you closed the page.

tobiaswer avatar Dec 07 '23 12:12 tobiaswer

Were you able to take a look at it @RobbeSneyders ?

tobiaswer avatar Mar 20 '24 16:03 tobiaswer