当前位置: 首页 > wzjs >正文

厚街网站建设公司网络培训学校

厚街网站建设公司,网络培训学校,郑州影视公司有哪些,温州网站建设咨询在 Python 中,上下文管理器(Context Manager) 是一种用于管理资源获取与释放的结构,核心作用是自动化资源的进入和退出(常用于文件操作、数据库连接、线程锁、事务处理等)。它的本质是定义好 enter / exit&…

在 Python 中,上下文管理器(Context Manager) 是一种用于管理资源获取与释放的结构,核心作用是自动化资源的进入和退出(常用于文件操作、数据库连接、线程锁、事务处理等)。它的本质是定义好 enter / exit(同步)或 aenter / aexit(异步) 方法。

1. 基本概念

同步上下文管理器(with)

class MyResource:def __enter__(self):print("获取资源")return selfdef __exit__(self, exc_type, exc_val, exc_tb):print("释放资源")with MyResource() as r:print("处理中")

输出:

获取资源
处理中
释放资源

异步上下文管理器(async with)

适用于异步资源(如:异步数据库、aiofiles、aiohttp 等):

class MyAsyncResource:async def __aenter__(self):print("异步获取资源")return selfasync def __aexit__(self, exc_type, exc_val, exc_tb):print("异步释放资源")async with MyAsyncResource() as r:print("异步处理中")

2. contextlib 模块

contextlib 是 Python 标准库中的一个实用工具模块,专门用于简化上下文管理器(context manager)的创建和使用。

主要功能

  1. 简化上下文管理器的创建 - 无需编写完整的类实现 enterexit 方法
  2. 提供装饰器和工具函数 - 用于常见上下文管理场景
  3. 支持可重用的上下文管理器

核心组件

1. @contextmanager 装饰器

基本用法:

from contextlib import contextmanager@contextmanager
def 管理资源(*args, **kwargs):# 这部分相当于 __enter__ 方法资源 = 获取资源(*args, **kwargs)try:yield 资源  # 在这里返回资源给as变量finally:# 这部分相当于 __exit__ 方法释放资源(资源)# 使用方式
with 管理资源() as 资源:print(资源)

示例:

from contextlib import contextmanager@contextmanager
def open_file(path):f = open(path, 'r')try:yield ffinally:f.close()with open_file("test.txt") as f:print(f.read())

2. @asynccontextmanager(异步)

基本用法:

from contextlib import asynccontextmanager@asynccontextmanager
async def async_resource_manager():# 初始化部分 (相当于 __aenter__)resource = await acquire_resource_async()try:yield resource  # 在这里暂停,将资源提供给 with 块finally:# 清理部分 (相当于 __aexit__)await release_resource_async(resource)# 使用方式
async def main():async with async_resource_manager() as res:await do_something_with(res)

特点:

  • 专为异步代码设计:与普通 @contextmanager 不同,它处理的是异步上下文协议 (aenter/aexit)
  • 必须用 async with 调用:不能与普通 with 语句混用
  • 支持异步清理:finally 块中可以执行 await 操作

示例:

from contextlib import asynccontextmanager
import aiofiles@asynccontextmanager
async def open_file_async(path):f = await aiofiles.open(path, 'r')try:yield ffinally:await f.close()async def run():async with open_file_async("test.txt") as f:content = await f.read()

3. 高级实践:FastAPI 启动生命周期封装

from fastapi import FastAPI
from contextlib import asynccontextmanager
from motor.motor_asyncio import AsyncIOMotorClient@asynccontextmanager
async def lifespan(app: FastAPI):app.state.mongo = AsyncIOMotorClient("mongodb://localhost:27017")["mydb"]yieldapp.state.mongo.client.close()app = FastAPI(lifespan=lifespan)
http://www.dtcms.com/wzjs/478484.html

相关文章:

  • 网站首页设计收费手机制作网站app
  • 做网站好的网站建设公司二十条优化措施全文
  • 淘宝网站咋做我想接app注册推广单
  • 网站建设经费预算包括哪些百度手机端推广
  • wordpress建站 评测企业高管培训课程有哪些
  • 密云网站建设痘痘怎么去除效果好
  • 泉州企业网站开发全域seo
  • 做婚纱网站的步骤销售怎么做
  • 互联网 网站建设价格企业培训课程种类
  • 广东网站建设包括什么子域名在线查询
  • 网站建设怎么样让图片翻滚成都网站建设软件
  • 今天最新新闻报道seo怎么刷排名
  • 东莞做网站建设微博推广平台
  • 网站布局是什么样的全媒体运营师报考条件
  • 椒江网站建设578做网站fba欧美专线
  • 做空比特币的网站seo sem关键词优化
  • 亲子装网站建设职业技能培训有哪些
  • 做网站能用假图片吗网站优化方案怎么写
  • 本网站服务器设在美国服务器保护网上找客户有什么渠道
  • dwcs3做网站广东seo推广哪里好
  • 手机域名注册网站成都百度seo公司
  • 淄博网站建设网站推广优化优化大师使用方法
  • 兴义党风廉政建设网站杭州seo公司哪家好
  • 做除尘环保的如何推广自己的网站怎样建立一个网络销售平台
  • 求大神帮忙做网站厦门seo代理商
  • 南京 郑州网站建设公司 网络服务太原企业网站建设
  • wordpress 访问页面空白针对百度关键词策划和seo的优化
  • 商贸网站建设南昌seo全网营销
  • 企业网站模板html推广平台
  • 合作网站建设网络营销推广的要点