Not sure, that this is possible, but still
I have default async FastAPI application, where I have sync function
@classmethod
def make_values(
cls,
records: list,
symbol: str = None,
) -> list:
values = []
for record in records:
new_row = SomePydanticModel(
timestamp=record._mapping.get("time"),
close=record._mapping.get("close"),
value=record._mapping.get("value"),
)
if symbol in EXTRA_SYMBOLS:
new_row = split_row(new_row, symbol)
values.append(new_row)
return values
The problem is that split_row
is async function, that calls other async functions
async def split_row(
row,
symbol,
):
adjusted_datetime = datetime.timestamp(datetime.strptime("01/01/19", "%m/%d/%y"))
splits = await get_splits(symbol)
# some big part with business logic with other async calls
return row
Currently I get coroutine in new_row
variable. Is there anyway to get the result of split_row?
async
/await
and how FastAPI/Starlette works under the hood.loop.run_in_executor()
and run theasync
function usingasyncio.run()
in a separate Thread, as shown in this answer. Still, I would highly suggest thoroughly reading the linked answer above.values
is a list of coroutines. Instead of declaringmake_values
async def, you could passvalues
up the call stack until you reach an async function. Unlessmake_values
is a callback, there must be an async function somewhere up the stack (since you have a running event loop). You could then await the list ofvalues
at that point. No matter what you do, somewhere you have to await each element ofvalues
. Becausesplit_row
is async, it cannot return a meaningful result without yielding to the event loop at least once.