Replies: 2 comments
-
I was able to get this to work by creating a new user instance from a new session, but unsure why the above stopped working 🤷 async def on_after_register(self,
user: User,
request: Optional[Request] = None):
# TODO: update launch.json to include env var for sending verification email
if os.environ.get("SEND_VERIFICATION_EMAIL", "false") == "true":
response = await self.request_verify(user=user)
return response
else:
logger.info(f"Setting user {user.id} as verified")
user.is_verified = True
# Get a fresh session and update the user
async with async_session_maker() as session:
# Fetch the user from the database
db_user = await session.get(User, user.id)
if db_user:
db_user.is_verified = True
await session.commit()
logger.info(f"User {user.id} verified status updated in database")
else:
logger.error(f"Could not find user {user.id} in database")
# Return success message
return {"message": "User registered successfully"} |
Beta Was this translation helpful? Give feedback.
-
Depends should be used at the routing level, not within the methods executed later. The You can try rewriting the create method: Alternatively, you can subclass The code looks something like this, although I haven't actually run it — but it should work. class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
def __init__(self, session: AsyncSession, **kwargs):
super().__init__(**kwargs)
self.session = session
async def on_after_register(self, user: User, request: Optional[Request] = None):
print(f"User {user.id} has registered.")
if os.environ.get("SEND_VERIFICATION_EMAIL", "false") == "true":
response = await self.request_verify(user=user)
return response
else:
user.is_verified = True
self.session.add(user)
await self.session.commit()
return {"message": "User registered successfully"}
async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db), session: AsyncSession = Depends(get_async_session)):
yield UserManager(user_db=user_db, session=session) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Returning to a project I haven't touched in a minute, but having a new issue that I swear wasn't happening before
I'm trying to access my sqlalchemy database session after registering a user
But when I call
session.add
I get an exception - for some reason I'm not getting the session object I used to getI don't have the same issue when using Depends in routes, but for some reason the above exception appeared out of nowhere
I've tried to create a new async session and use that, but I then get an exception that the user object is connected to another session, I presume the one used to create the use and add to the database
Beta Was this translation helpful? Give feedback.
All reactions