#๐Ÿ”’ Sqlalchemy 2 with AsyncSession

4 messages ยท Page 1 of 1 (latest)

twin beacon
#

I'm trying to make working postgresql database with sqlalchemy2 with async sessionmaker. Before i used concurent session which was without problem.
Now to my problem.

I've got this table

class GuildDB(database.base):
    __tablename__ = "guild"

    id: Mapped[str] = mapped_column(primary_key=True)
    phrases: Mapped[set[GuildPhraseDB]] = relationship(back_populates="guild", cascade="all, delete", collection_class=set, lazy="selectin")
    info_channel_id: Mapped[str] = mapped_column(nullable=True)

    @hybrid_property
    async def phrases_dict_prop(self) -> dict[str, str]:
        return {phrase.key: phrase.value for phrase in self.phrases}

    @classmethod
    async def get_guild(cls, guild_id: str) -> GuildDB:
        async with database.get_session() as session:
            guild = await session.get(cls, guild_id)
            if not guild:
                guild = await cls.add_guild(guild_id)
            return guild

   @classmethod
    async def add_guild(cls, guild_id: str) -> GuildDB:
        async with database.get_session() as session:
            guild = cls(id=guild_id)
            session.add(guild)
            await session.commit()
            return guild

Whenever i try to access the phrases_dict_prop

guild = await GuildDB.get_guild(guild_id)
print(await guild.phrases_dict_prop)

i get

Parent instance <GuildDB at 0x783323209be0> is not bound to a Session; lazy load operation of attribute 'phrases' cannot proceed

My session maker

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from config.app_config import config

class Database:
    def __init__(self):
        self.base = declarative_base()
        self.engine = create_async_engine(config.db_string, echo=False)
        self.session = sessionmaker(self.engine, expire_on_commit=False, class_=AsyncSession)
    
    def get_session(self) -> AsyncSession:
        return self.session()

database = Database()

I had the impression that setting the relationship it to lazy="selectin" with expire_on_commit=False would make it possible

prime spokeBOT
#

@twin beacon

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

prime spokeBOT
#

@twin beacon

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.