how to use a custom io take in fastapi #7828
Replies: 14 comments
-
What do you want? |
Beta Was this translation helpful? Give feedback.
-
`import time app = FastAPI() def io(): @app.get('/') |
Beta Was this translation helpful? Give feedback.
-
like this |
Beta Was this translation helpful? Give feedback.
-
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} |
Beta Was this translation helpful? Give feedback.
-
for examples?thanks。。 |
Beta Was this translation helpful? Give feedback.
-
Do not use async to define the view function with its own blocking task? |
Beta Was this translation helpful? Give feedback.
-
意思是有自己的阻塞任务的视图函数就不要使用async 定义函数么 |
Beta Was this translation helpful? Give feedback.
-
Yes. You should mark your functions by just |
Beta Was this translation helpful? Give feedback.
-
and i can write a ThreadPoolExecutor to run io()? |
Beta Was this translation helpful? Give feedback.
-
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 |
Beta Was this translation helpful? Give feedback.
-
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 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, |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help @prostomarkeloff and @sm-Fifteen 🙇♂️ 🍰 |
Beta Was this translation helpful? Give feedback.
-
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
-
Description
How can I [...]?
how to use a custom io take in fastapi?
I can't get the event_loop out......
Beta Was this translation helpful? Give feedback.
All reactions