I’m new to SQLAlchemy in general, and even more to its asyncio mode.
I’m creating an async session like so (demo/pseudo code):
<code>async_scoped_session(
async_sessionmaker(
bind=create_async_engine(
format_db_url(CONFIG)
)
),
scopefunc=asyncio.current_task
)
</code>
<code>async_scoped_session(
async_sessionmaker(
bind=create_async_engine(
format_db_url(CONFIG)
)
),
scopefunc=asyncio.current_task
)
</code>
async_scoped_session(
async_sessionmaker(
bind=create_async_engine(
format_db_url(CONFIG)
)
),
scopefunc=asyncio.current_task
)
and then creating a model like so:
<code> ...
async def model(self):
model = TestUser(name='test', age=1)
self.session.add(model)
await self.session.commit()
return model
...
</code>
<code> ...
async def model(self):
model = TestUser(name='test', age=1)
self.session.add(model)
await self.session.commit()
return model
...
</code>
...
async def model(self):
model = TestUser(name='test', age=1)
self.session.add(model)
await self.session.commit()
return model
...
but, when trying to use it:
<code>model = repo.model()
print(model.name)
</code>
<code>model = repo.model()
print(model.name)
</code>
model = repo.model()
print(model.name)
it fails at the print with:
<code>sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)
</code>
<code>sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)
</code>
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)
These two adjustments fix the issue:
<code>await repo.session.refresh(model)
# and/or
id_ = await model.awaitable_attrs.name
</code>
<code>await repo.session.refresh(model)
# and/or
id_ = await model.awaitable_attrs.name
</code>
await repo.session.refresh(model)
# and/or
id_ = await model.awaitable_attrs.name
But I have the feeling I’m missing something or doing something wrong, I kinda understand the need for awaitable_attrs
when accessing a relationship, but it doesn’t feel right having to an extra step before being able to access a model’s own attribute.