flask上下文管理:
类方法中有__enter__和__exit__两个方法,可以使用with,管理上下文
- 应用上下文 对象 Flask封装(current_app)代理模式
- 请求上下文 对象 Request封装(request)
- Flask AppContext 应用上下文
- Request RequestContext 请求上下文
- 通过上下文获取flask和request核心对象
- 离线应用,单元测试
示例:
class MyResource:
# 上下文管理 with语句
def __enter__(self):
print('connect to resource')
return self
# a = 1
def __exit__(self, exc_type, exc_val, exc_tb):
print('closed resource connection')
# b = 2
if exc_tb:
print('process exception')
else:
print('no exception')
print('closed resource connection')
return True # 返回Flase或什么都不返回在with外部还会抛出异常,True不会再返回异常
def qu