python - 用于 asyncpg 的 Python 上下文管理器
问题描述
我正在尝试为 asyncpg 构建一个上下文管理器,但到目前为止,我得到了AttributeError: __enter__
,这就是我尝试过的。我试过在def __enter__
没有异步的情况下使用,但不起作用
什么是正确的方法?
import asyncpg
import asyncio
class DatabaseConnection(object):
def __init__(self, host, port, database, user, password):
self.connection = None
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
async def __aenter__(self):
self.connection = await asyncpg.connect(host=self.host,
port=self.port,
database=self.database,
user=self.user,
password=self.password)
return self.connection
async def __aexit__(self, exc_type, exc_val, exc_tb):
# its executed when connection close
self.connection.close()
然后尝试使用它
async def get_time():
with DatabaseConnection(host=DB_HOST, port=DB_PORT,
database=DB_NAME, user=DB_USER,
password=DB_PASSWORD) as connection:
values = await connection.fetch('''SELECT * CURRENT_TIME''')
print(values)
loop = asyncio.get_event_loop()
loop.run_until_complete(get_time())
解决方案
推荐阅读
- python - 过滤日期时间字段python
- google-chrome - 量角器 - 错误代码 199:Chrome 版本不支持 84 版
- c - C中的浮点异常(核心转储)
- typo3 - TYPO3 多个嵌套的 DatabaseQueryProcessor
- c# - 自定义 JSON 合同解析器忽略所有没有自定义注释的属性
- python - <403> API URL 的响应 Python Scrapy/Request
- f# - paket - 如何将包安装到项目的本地文件夹
- css - Webpack + 反应。如何预加载主 CSS 文件?
- php - php artisan migrate 的 MySQL 错误
- javascript - 切片 JSON 数组并随机连接 2 个数据对——简单还是困难?