FastAPI之阻塞式io和非阻塞式io

import time
import asyncio
from fastapi import FastAPI

app = FastAPI()

'''
并发两个请求:阻塞式io,uvicorn开启的一个线程无法同时执行两个请求,只能一个完成再执行另一个
请求1:
    hello
    bye
请求2:
    hello
    bye
'''
@app.get('/1')
async def t1():
    print('hello')
    time.sleep(5)
    print('bye')

'''
并发两个请求:非阻塞式io,uvicorn开启的一个线程遇到非阻塞io,协程会切换到另一个请求上执行,出现如下效果
请求1:
    hello
请求2:
    hello
请求1:
    bye
请求2:
    bye
'''
@app.get('/2')
async def t2():
    print('hello')
    await asyncio.sleep(5)
    print('bye')

'''
并发两个请求:阻塞式io,使用的是def,会开启两个线程执行视图函数,所以会出现如下效果
请求1:
    hello
请求2:
    hello
请求1:
    bye
请求2:
    bye
'''
@app.get('/3')
def t3():
    print('hello')
    time.sleep(5)
    print('bye2')
    
'''


'''

posted @ 2024-07-05 22:05  刘清政  阅读(25)  评论(0编辑  收藏  举报