代码之家  ›  专栏  ›  技术社区  ›  hanover

如何异步使用fastapi

  •  0
  • hanover  · 技术社区  · 3 年前

    服务器.py

    from fastapi import FastAPI
    
    import uvicorn
    import time
    
    app = FastAPI()
    
    @app.post('/upload')
    async def upload(file: dict):
        print('hello')
    
        time.sleep(1)
        
        return file
    
    if __name__ == '__main__':
        uvicorn.run(app, host='', port=1024)
    

    客户端.py

    import requests
    import threading
    
    def thread_main(a):
        response = requests.post(url, json={'0':0, '1':1, '2':2})
        if response.status_code == 200:
            print(a, response.json())
        else:
            print(a, 'wrong')
    
    url = 'http://IP:1024/upload'
    for i in range(10):
        thread = threading.Thread(target=thread_main, args=(i,))
        thread.start()
    

    服务器日志 “” 你好 信息:IP:port-“POST/upload HTTP/1.1”200 OK 你好 信息:IP:port-“POST/upload HTTP/1.1”200 OK 你好 信息:IP:port-“POST/upload HTTP/1.1”200 OK 。。。 “”

    但我希望他们是 “” 你好 你好 你好 。。。 信息:IP:port-“POST/upload HTTP/1.1”200 OK 信息:IP:port-“POST/upload HTTP/1.1”200 OK 信息:IP:port-“POST/upload HTTP/1.1”200 OK 。。。 “”

    在fastapi中可能吗?

    我认为使用“async”意味着服务器异步处理请求,但事实并非如此

    此外,我如何知道该函数是否为阻塞函数?如何找到替代函数?

    1 回复  |  直到 3 年前
        1
  •  0
  •   kin4stat    3 年前

    您正在使用同步(阻塞) time.sleep(1) 内部异步函数。

    阻塞函数完全阻塞线程,这就是为什么无法执行此线程上的其他操作的原因

    在这种情况下,主线程的执行会被阻塞,直到time.sleep结束,并且在线程被阻塞时fastapi无法处理新的请求

    在这种特殊情况下,您需要使用异步延迟,也就是 asyncio.sleep

    服务器.py

    from fastapi import FastAPI
    
    import uvicorn
    import time
    import asyncio
    
    app = FastAPI()
    
    @app.post('/upload')
    async def upload(file: dict):
        print('hello')
    
        await asyncio.sleep(1)
        
        return file
    
    if __name__ == '__main__':
        uvicorn.run(app, host='', port=1024)