#🔒 SQL Alchemy Signals Help

22 messages · Page 1 of 1 (latest)

mystic blaze
#

I am trying to have signals using SQL Alchemy to use for WebSockets with FastAPI. I have now dumbed it down to try and just log a message whenever a new record is inserted but that isn't even working. Look below for relavent code.

session.py

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from app.core.config import settings

DATABASE_URL = settings.SQLALCHEMY_DATABASE_URI

engine = create_async_engine(DATABASE_URL)
AsyncSessionLocal = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

Base = declarative_base()

events.py

import logging

from sqlalchemy import event

from app.models import SMS

logger = logging.getLogger(__name__)


logger.info("Registering after_insert event listener for SMS.")


@event.listens_for(SMS, "after_insert")
def after_insert(mapper, connection, target):
    logger.info(f"New SMS inserted: {target.id}")
iron juniperBOT
#

@mystic blaze

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.

compact snow
#

I don't think you can listen for after_insert.

mystic blaze
#

So would I need to do a after_commit and then check which model performed said commit then apply my logic?

#

Also, could you send me the link to wherever you got that screenshot. Would be helpful.

compact snow
compact snow
mystic blaze
#

I think you are right.

compact snow
mystic blaze
#

So if I could just get info about the commit, like what model, object(s), etc. I should be able to do what I need right?
Side note, I was looking at using the Mapper Events. If you scroll down that same page you sent me.

compact snow
mystic blaze
#

That solution also suggests just using a whole different module for this.

compact snow
mystic blaze
#

Hey, sorry I had to step away for a meeting.

#

No SMS is a model.

mystic blaze
compact snow
mystic blaze
#

Ok, I tried it. Still no good.

iron juniperBOT
#
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.