首页 > 其他分享 >fastapi - 同步接口也不会有IO阻塞!

fastapi - 同步接口也不会有IO阻塞!

时间:2024-05-11 14:34:02浏览次数:19  
标签:index run thread 1715408207 fastapi 阻塞 IO timestamp id

之前一直以为FastAPI对于同步IO会发生服务阻塞,直到今天看到了这一块代码,原来同步的函数会开线程去处理

fastapi/routing.py

async def run_endpoint_function(
    *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool
) -> Any:
    # Only called by get_request_handler. Has been split into its own function to
    # facilitate profiling endpoints, since inner functions are harder to profile.
    assert dependant.call is not None, "dependant.call must be a function"

    if is_coroutine:
        return await dependant.call(**values)
    else:
        return await run_in_threadpool(dependant.call, **values)

starlette/concurrency.py

async def run_in_threadpool(
    func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs
) -> T:
    if kwargs:  # pragma: no cover
        # run_sync doesn't accept 'kwargs', so bind them in here
        func = functools.partial(func, **kwargs)
    return await anyio.to_thread.run_sync(func, *args)

这么一来的话其实即使是同步IO也不至于严重影响FastAPI的性能,那么对于并发要求不是很高的项目也可以用传统的同步IO库去开发了 -

专门做了一个anyio.to_thread.run_sync的测试

import time
import asyncio
from threading import current_thread

from anyio import to_thread, run


def work(i):
    time.sleep(3)
    print(f"{i}(index) {int(time.time())}(timestamp) {current_thread().native_id}(thread_id)")


async def main():
    coroutines = []
    for i in range(10):
        coroutines.append(to_thread.run_sync(work, i))
    await asyncio.gather(*coroutines)


run(main)
0(index) 1715408207(timestamp) 5642751(thread_id)
5(index) 1715408207(timestamp) 5642756(thread_id)
1(index) 1715408207(timestamp) 5642752(thread_id)
2(index) 1715408207(timestamp) 5642753(thread_id)
4(index) 1715408207(timestamp) 5642755(thread_id)
6(index) 1715408207(timestamp) 5642757(thread_id)
8(index) 1715408207(timestamp) 5642759(thread_id)
7(index) 1715408207(timestamp) 5642758(thread_id)
9(index) 1715408207(timestamp) 5642760(thread_id)
3(index) 1715408207(timestamp) 5642754(thread_id)

确实可以并发!

标签:index,run,thread,1715408207,fastapi,阻塞,IO,timestamp,id
From: https://www.cnblogs.com/houchuanqi/p/18186413

相关文章

  • u-radio-group 与 radio-group,u-radio与radio,u-checkbox-group与checkbox-group、u-ch
    回显问题:官方的回显没有uview的回显好用<u-radio-group@change="selfInjuryChange"placement="column"v-model="model.abilityAssessmentInfoDTO.idioctonia"><viewv-for="(item,index)infallList":......
  • fastapi - 获取token
    在FastAPI通过标注Header类型获取Authorization时,会导致openapi页面的请求没法使用fromtypingimportAnnotatedfromfastapiimportFastAPI,Header,Request,Depends,Cookie,Query,APIRouterfromfastapi.routingimportAPIRoutefromfastapi.security.api_keyim......
  • CentOs上安装minio
    MINIO安装一、下载二进制文件wgethttps://dl.minio.org.cn/server/minio/release/linux-amd64/minio 二、授权,并移动到指定目录chmod+xminiosudomvminio/usr/local/bin/ 二、创建服务文件/usr/lib/systemd/system/minio.service 内容如下: [Unit]Descripti......
  • nRF51_Platform - 基于nRF51平台(蓝牙4.0)的轻量级SDK+AliOS Things - 阿里出品轻量级
    1、AliOSThings-阿里出品轻量级物联网嵌入式操作系统AliOSThings发布于2017年杭州云栖大会,是AliOS家族旗下的、面向IoT领域的、高可伸缩的物联网操作系统。AliOSThings致力于搭建云端一体化IoT基础设施,具备极致性能、极简开发、云端一体。项目主页: https://github.c......
  • SciTech-Mathmatics-ProbabilitiesAndStatistics-Distribution-is-all-you-need: 概率
    Distribution-is-all-you-need概率统计到深度学习,四大技术路线图谱,都在这里!https://github.com/graykode/distribution-is-all-you-need自然语言处理路线图:数学基础->语言基础->模型和算法项目作者:Tae-HwanJung,Github:graykode,2019-09-3013:35,选自Github自然......
  • Fibocom L830 是一款移动通信模块,通常用于嵌入式设备或物联网(IoT)应用中。它提供了蜂窝
    驱动程序下载FibocomL830是一款移动通信模块,通常用于嵌入式设备或物联网(IoT)应用中。它提供了蜂窝连接功能,支持4GLTE网络,并具有全球覆盖的能力。这种模块通常被嵌入到各种设备中,例如智能手表、智能家居设备、工业设备等,以便这些设备可以通过蜂窝网络进行通信和远程控制。关于......
  • FastAPI 创建
    1.安装FastAPI和Uvicorn:pipinstallfastapiuvicorn2.创建FastAPI应用。main.py:fromfastapiimportFastAPIapp=FastAPI()@app.get("/")defread_root():return{"Hello":"World"}3.在命令行中使用Uvicorn启动你的应用:uv......
  • FastApi-tortoise-jwt-mysql
    抽了半天时间学了一下fastapi,为了方便,代码没分结构。importsysimportjwtimportuvicorn,asyncio,signal,osfromfastapiimportFastAPI,HTTPException,Dependsfromfastapi.securityimportOAuth2PasswordBearer,OAuth2PasswordRequestFormfromtortoiseimportfie......
  • 文件IO学习【三】
    目录系统IO接口说明概念解释标准IO和系统IO的区别常用系统IO函数介绍打开文件关闭文件文件读取文件写入位置偏移系统IO接口说明概念解释由于Linux系统下“一切皆文件”,也就是Linux系统下的数据和程序都是以文件的形式存储的,所以Linux内核会提供一组操作文件的函数接口,这组函数......
  • 使用stable diffusion设计logo的提示词
    使用stablediffusion设计logo的提示词StableDiffusion是一种基于图像处理和机器学习的算法,可以用于生成各种类型的图像,包括Logo设计。本文将介绍如何使用StableDiffusion来设计Logo,并提供一些提示词以帮助读者更好地理解和应用这种技术。1.了解StableDiffusion的基本原理在......