Fastapi: [BUG] using yield in route

Created on 14 Apr 2020  路  6Comments  路  Source: tiangolo/fastapi

Describe the bug

I am not sure if it is a bug, or a feature request. Perhaps using yield in a route is not intended by fastapi.

To Reproduce

  1. Create a file with:
@app.get("/")
async def root():
    print('hello')
    yield JSONResponse({'some': 'text'})
    print('world')

  1. Open the browser and call the endpoint /.

Expected behaviour

The {'some': 'text'} as json.

Screenshots

But this is what I get.

image

Environment

  • Linux Mint 19
  • Fastapi 0.54.1
answered question

All 6 comments

As for as i know FastAPI is not support "yield" response. Use "return" instead of "yield". 馃榿

If you want to do something after send a response.
You can try background task

@Maklero Well there is a reason I wanted to use yield and not return ;D

@Dustyposa Thanks I will give it a try

Thanks for the help here everyone! :clap: :bow:

Thanks for reporting back and closing the issue @HuiiBuh :+1:

@tiangolo Just out of interest. Do you consider supporting yield as response?

@HuiiBuh nope, it wouldn't really make sense, it would add another layer of complexity that wouldn't help much. And it would make the code look as if it was doing something different than it does.

As @Dustyposa says, that would probably belong to BackgroundTasks, it would work better there :rocket: https://fastapi.tiangolo.com/tutorial/background-tasks/

Was this page helpful?
0 / 5 - 0 ratings