Fastapi: [QUESTION] how to use a custom io take in fastapi

Created on 27 Nov 2019  ·  14Comments  ·  Source: tiangolo/fastapi

Description

How can I [...]?

how to use a custom io take in fastapi?
I can't get the event_loop out......

question

All 14 comments

What do you want?

`import time
from fastapi import FastAPI
import asyncio

app = FastAPI()

def io():
time.sleep(1)
return None

@app.get('/')
async def index():
# i want to use io() by async ,but i cant
io()
return {‘xx’:''xx}
`
``

like this

You can. Just define your route-function as synchronous and fastapi will run it in threadpool.

import time
from fastapi import FastAPI
import asyncio

app = FastAPI()

def io():
time.sleep(1)
return None

@app.get('/')
def index():
io()
return {‘xx’:''xx}

for examples?thanks。。

Do not use async to define the view function with its own blocking task?

意思是有自己的阻塞任务的视图函数就不要使用async 定义函数么

Do not use async to define the view function with its own blocking task?

Yes. You should mark your functions by just def if you want to do inside blocking operations.

and i can write a ThreadPoolExecutor to run io()?

and i can write a ThreadPoolExecutor to run io()?

No, you just should write blocking code like this:

# some definitions, etc.

@app.get("/")
def index():
    result = blocking_io()
    return {"result": result}

FastAPI will run your code in ThreadPoolExecutor by self.

Thanks

You can also make your own custom async I/O functions, but those would have to either rely on async libraries (like httpx, aiohttp, aiofiles, asyncpg, etc.) or use Python asyncio's own "leaf futures" (the primitive IO functions those libraries are built upon) like asyncio.sleep(), asyncio.open_connection(), and so on. You'll probably want to use libraries, though, the asyncio primitives can be difficult to work with.

from fastapi import FastAPI
import asyncio

app = FastAPI()

async def io():
    await asyncio.sleep(1) # Don't forget to await your async I/O functions!
    return 'xx'

@app.get('/')
async def index():
    result = await io() # You have to await any function marked as `async def`
    return {'xx':result}

Using one or the other shouldn't cause much difference for you, though,

Thanks for the help @prostomarkeloff and @sm-Fifteen :bowing_man: :cake:

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RenanAlonkin picture RenanAlonkin  ·  3Comments

DrPyser picture DrPyser  ·  3Comments

zero0nee picture zero0nee  ·  3Comments

updatatoday picture updatatoday  ·  3Comments

kkinder picture kkinder  ·  3Comments