You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I used the GitHub search to find a similar question and didn't find it.
I searched the FastAPI documentation, with the integrated search.
I already searched in Google "How to X in FastAPI" and didn't find any information.
I already read and followed all the tutorial in the docs and didn't find an answer.
I already checked if it is not related to FastAPI but to Pydantic.
I already checked if it is not related to FastAPI but to Swagger UI.
I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
I commit to help with one of those options 👆
Example Code
asyncdefasync_gen(camera: BaseCamera) ->Generator[bytes, None, None]:
"""Video streaming async generator function."""yieldb"--frame\r\n"try:
whileTrue:
jpeg=camera.get_frame_jpeg()
ifjpegisNone:
app_logger.debug("No jpeg frame available")
raiseV4L2Exception("No jpeg frame available")
else:
yieldTCPSocket.package_mjpeg(jpeg.data, jpeg.metadata)
# need this sleep in order to be able to catch the disconnectawaitasyncio.sleep(0)
exceptasyncio.CancelledError:
app_logger.debug("Client disconnected")
exceptExceptionase:
app_logger.debug(f"Unhandled exception in async_gen: {e}")
# how to return from here something that I can detect on `async_video_feed()`?classMJPEGResponse(StreamingResponse):
"""Custom response for MJPEG stream"""media_type="multipart/x-mixed-replace; boundary=frame"""": The returned media type"""# http://10.10.150.225:5000/mjpeg?dev=/dev/qtec/video0@router.get("/mjpeg", response_class=MJPEGResponse)asyncdefasync_video_feed(
params: CommonParams=Depends(), # noqa: B008
) ->MJPEGResponse:
"""Async video streaming route. Put this in the src attribute of an img tag. """try:
cam=Camera(device=params.dev, stream=True)
res=async_gen(cam)
# how can I detect errors in `async_gen()` from here?returnMJPEGResponse(res)
exceptV4L2Exceptionase:
raiseAPIV4L2Error(str(e)) fromeexceptRuntimeErrorase:
raiseAPIInputError(str(e)) fromeexceptExceptionase:
raiseAPIGenError(
f"{type(e).__name__} from {sys._getframe().f_code.co_name}(): {e}"
) frome@app.exception_handler(APIError)asyncdefunicorn_exception_handler(request: Request, exc: APIError):
"""Return custom JSON when APIError or its children are raised"""response= {"error": exc.description, "message": ""}
iflen(exc.args) >0:
response["message"] =exc.args[0]
app_logger.error(f"{exc.description}: {response['message']}")
returnJSONResponse(
status_code=exc.code,
content={"message": response},
)
Description
I have the following route and async generator for producing a MJPEG stream and it works.
My question is how can I propagate/display errors?
Fx. if I pass an invalid video device as the parameter here: http://10.10.150.225:5000/mjpeg?dev=/dev/qtec/video0, an Exception is generated by cam = Camera(device=params.dev, stream=True) and caught in the except V4L2Exception as e: and it gets handled by my exception_handler so that I get a JSON with the error message displayed on the browser.
So far so good.
My next problem is that if the video device is busy then the generator cannot generate the stream: jpeg = camera.get_frame_jpeg() returns None and in that case I would also like to be able to show a JSONResponse error in the browser.
I have tried many different iterations and can't seem to make it work.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
I have the following route and async generator for producing a MJPEG stream and it works.
My question is how can I propagate/display errors?
Fx. if I pass an invalid video device as the parameter here:
http://10.10.150.225:5000/mjpeg?dev=/dev/qtec/video0, an Exception is generated bycam = Camera(device=params.dev, stream=True)and caught in theexcept V4L2Exception as e:and it gets handled by myexception_handlerso that I get a JSON with the error message displayed on the browser.So far so good.
My next problem is that if the video device is busy then the generator cannot generate the stream:
jpeg = camera.get_frame_jpeg()returnsNoneand in that case I would also like to be able to show a JSONResponse error in the browser.I have tried many different iterations and can't seem to make it work.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.85.2
Pydantic Version
1.10.12
Python Version
Python 3.11.2
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions