aurweb/aurweb/models/session.py
Kevin Morris 51320ab22a
change(fastapi): unify all model relationship behavior
Now, we allow the direct relationships and their foreign keys to
be set in all of our models. Previously, we constrained this to
direct relationships, and this forced users to perform a query
in most situations to satisfy that requirement. Now, IDs can be
passed directly.

Additionally, this change removes the need for extraneous imports
when users which to use relationships. We now import and use models
directly instead of passing string-references to them.

Signed-off-by: Kevin Morris <kevr@0cost.org>
2021-10-16 16:24:00 -07:00

37 lines
1.1 KiB
Python

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import backref, relationship
from aurweb.db import make_random_value, query
from aurweb.models.declarative import Base
from aurweb.models.user import User as _User
class Session(Base):
__tablename__ = "Sessions"
UsersID = Column(
Integer, ForeignKey("Users.ID", ondelete="CASCADE"),
nullable=False)
User = relationship(
_User, backref=backref("session", uselist=False),
foreign_keys=[UsersID])
__mapper_args__ = {"primary_key": [UsersID]}
def __init__(self, **kwargs):
super().__init__(**kwargs)
user_exists = query(
query(_User).filter(_User.ID == self.UsersID).exists()
).scalar()
if not user_exists:
raise IntegrityError(
statement=("Foreign key UsersID cannot be null and "
"must be a valid user's ID."),
orig="Sessions.UsersID",
params=("NULL"))
def generate_unique_sid():
return make_random_value(Session, Session.SessionID)