个人总结
command.py
file.py
time.py
excel.py
with 的原理和用法
subprocess 模块
cline 提示词
PathLike
pathlib
peewee
生成随机ID
FastApi 使用 peewee
http connect
Dataframe Protocol
pyarrow
overload 函数重载
1111
peewee 线程安全
Python 日志模块
rabbitmq 问答
多进程 daemon 参数
记录异常
dict.py
多进程
忽略异常
timer.py
Ctrl+C 退出while
发布pip包
Bolo组件
迭代器与生成器
dataclass
单例模式(二)
单例模式(一)
errors.py
enum.py
每日学习
本文档使用 MrDoc 发布
-
+
首页
with 的原理和用法
### with 的原理 如果一个对象需要使用with,那么它必须实现__enter__, __exit__这两个方法。 ``` class Sample: def __init__(self): pass def __enter__(self): print("in __enter__") return self def __exit__(self, ex_type, ex_val, ex_tb): print("in __exit__") ``` - 当执行 `with Sample() as obj` 语句时,对象会被创建,并且__enter__方法被调用,`obj`就是该方法的返回值; - 在退出with语句时,__exit__方法被调用,可以用来保证一些资源的释放; ### with 的使用 #### 场景一:限制同时上传文件的数量 因为服务器的内存有限,如果很多人同时上传文件,会导致服务器内存崩溃,因此需要限制同时上传的数量。 ``` class UploadCountHandler(object): def __init__(self, cache: Cache, user_uid): self.cache = cache self.user_uid = user_uid def __enter__(self): # 增加上传数量 self.cache.incr_upload_count_all() self.cache.incr_upload_count_user(user_uid=self.user_uid) def __exit__(self, ex_type, ex_val, ex_tb): # 减少上传数量 self.cache.decr_upload_count_all() self.cache.decr_upload_count_user(user_uid=self.user_uid) ``` #### 场景二:在指定目录中执行命令,执行完退出该目录 ``` class EnterFolder(object): def __init__(self, folder, make=False): if not make: if not os.path.isdir(folder): raise NotADirectoryError("folder {} not found".format(folder)) self.folder = folder def __enter__(self): cd(self.folder) def __exit__(self, ex_type, ex_val, ex_tb): cd("../") with EnterFolder(project.name): project.buildProject() project.buildImage(tag="1.0") with EnterFolder("images", make=True): project.saveImage(tag="1.0") ``` ##### 场景三:对于耗时较长的任务,记录时间和状态 ``` class DB(object): def __init__(self): self.path = ".mkzip.db" self.data = {} self.load() @property def build_status(self): return self.data.get("build_status", 0) def load(self): with open(self.path, "r+") as f: content = f.read() if not content: return self.data = json.loads(content) def save(self): with open(self.path, "w+") as f: f.write(json.dumps(self.data)) def __enter__(self): if self.data.get("build_status") == 1: raise Exception("已经在构建了,请稍等") self.data["build_status"] = 1 self.data["build_time"] = datetime.now().strftime("%m/%d %H:%M") self.save() def __exit__(self, ex_type, ex_val, ex_tb): print(ex_type, ex_val) if not ex_val: self.data["build_status"] = 2 self.save() with DB(): folder_path = PROJECT_HOME + project_name tar(["czf", f"{project_name}.tgz", f"{project_name}"], cwd=folder_path) zip("-r", f"{project_name}.zip", f"{project_name}", cwd=PROJECT_HOME) ```
gaojian
2021年10月29日 10:24
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
Markdown文件
分享
链接
类型
密码
更新密码