我正在使用带有asyncio
+ asyncpg
+ gino
(ORM-ish)+ aiohttp
(路由,网络响应)的Postgres,Python3.7。
我在数据库users
中创建了一个小的postgres表testdb
,并插入了一行:
testdb=# select * from users;
id | nickname
----+----------
1 | fantix
我正在尝试建立数据库,以便可以在请求进入时在路由内使用ORM。
import time
import asyncio
import gino
DATABASE_URL = os.environ.get('DATABASE_URL')
db = gino.Gino()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer(), primary_key=True)
nickname = db.Column(db.Unicode(), default='noname')
kwargs = dict(
min_size=10,
max_size=100,
max_queries=1000,
max_inactive_connection_lifetime=60 * 5,
echo=True
)
async def test_engine_implicit():
await db.set_bind(DATABASE_URL, **kwargs)
return await User.query.gino.all() # this works
async def test_engine_explicit():
engine = await gino.create_engine(DATABASE_URL, **kwargs)
db.bind = engine
async with engine.acquire() as conn:
return await conn.all(User.select()) # this doesn't work!
users = asyncio.get_event_loop().run_until_complete(test_engine_implicit())
print(f'implicit query: {users}')
users = asyncio.get_event_loop().run_until_complete(test_engine_explicit())
print(f'explicit query: {users}')
输出为:
web_1 | INFO gino.engine._SAEngine SELECT users.id, users.nickname FROM users
web_1 | INFO gino.engine._SAEngine ()
web_1 | implicit query: [<db.User object at 0x7fc57be42410>]
web_1 | INFO gino.engine._SAEngine SELECT
web_1 | INFO gino.engine._SAEngine ()
web_1 | explicit query: [()]
这很奇怪。本质上,“显式”代码对数据库运行裸SELECT
,这是没有用的。
我在文档中找不到两种方法:1)使用ORM,以及2)从池中明确检出连接。
我有问题:
await User.query.gino.all()
是否从池中检出连接?如何发布? 我本质上希望test_engine_explicit()
中样式的明确性可以与Gino一起使用,但是也许我只是不了解Gino ORM的工作方式。
答案 0 :(得分:1)
我以前从未使用过GINO,但是在快速浏览一下代码之后:
User.select()
,则不会增加任何内容。User.query.gino.all()
相同的功能,但自己维护连接,则可以follow the docs并使用User.query
而不是普通的User.select()
:async with engine.acquire() as conn:
return await conn.all(User.query)
经过测试,对我来说很好。
关于连接池,我不确定我是否正确地提出了问题,但是Engine.acquire
creates a reusable connection by default然后将其添加到池中,该池实际上是一个堆栈:
:param reusable: Mark this connection as reusable or otherwise. This has no effect if it is a reusing connection. All reusable connections are placed in a stack, any reusing acquire operation will always reuse the top (latest) reusable connection. One reusable connection may be reused by several reusing connections - they all share one same underlying connection. Acquiring a connection with ``reusable=False`` and ``reusing=False`` makes it a cleanly isolated connection which is only referenced once here.
在GINO中还有一个manual transaction control,例如您可以手动创建不可重用,不可重用的连接并控制交易流:
async with engine.acquire(reuse=False, reusable=False) as conn:
tx = await conn.transaction()
try:
await conn.status("INSERT INTO users(nickname) VALUES('e')")
await tx.commit()
except Exception:
await tx.rollback()
raise
关于连接释放,我找不到GINO本身释放连接的任何证据。我猜该池是由SQLAlchemy核心维护的。
我当然没有直接回答您的问题,但希望它能以某种方式对您有所帮助。