1

I am trying to receive body parameters from ajax call without using async on backend route.

When doing async It is working fine:

@app.post('/process-form')
async def process_form(request : Request):
    # Access form data
    form_data = await request.body()
    da = jsonable_encoder(form_data)
    print(da)

But without async body() does not exist (vs code debugger) and it is awaitable or something:

@app.post('/process-form')
def process_form(request : Request):
    # Access form data
    form_data = request.body()
    da = jsonable_encoder(form_data)
    print(da)
site-packages\anyio\streams\memory.py", line 89, in receive_nowait
    raise WouldBlock
anyio.WouldBlock

Why is it so and how Could I receive my data from request?

Tomas Am
  • 433
  • 4
  • 13

2 Answers2

1

Does the following code accomplish what you are looking for?

# foo.py

from asyncio import run
from fastapi import FastAPI, Request

app = FastAPI()

@app.post('/')
def process_form(request: Request):
    body = run(request.body())
    print(body)

I run the app with:

$ uvicorn --host 0.0.0.0 --port 9999 --reload foo:app

And test with:

$ curl http://localhost:9999/ -XPOST --data-raw 'hello world'

The key is to use asyncio.run (documentation for python3.9) to "execute synchronously" coroutines and tasks.

Nathan Chappell
  • 2,099
  • 18
  • 21
0

You can do this to have a sync end-point and access the payload:

@app.post('/process-form')
def process_form(form_data: Any, request : Request):
    # Access form data
    print(form_data)

form_data will contain the data you send as a payload to your request. You'll need to correctly type form_data

I think this post is similar to your question Using FastAPI in a sync way, how can I get the raw body of a POST request?

Sorix
  • 850
  • 5
  • 18