Spaces:
Sleeping
Sleeping
File size: 1,036 Bytes
5a2b2d3 9c7476c 5a2b2d3 9c7476c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from sqlalchemy.orm import Session
import models, schemas
def get_or_create_user(db: Session, username: str):
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
user = models.User(username=username)
db.add(user)
db.commit()
db.refresh(user)
return user
def add_message(db: Session, message: schemas.MessageBase, username: str):
# TODO: Implement the add_message function. It should:
# - get or create the user with the username
# - create a models.Message instance
# - pass the retrieved user to the message instance
# - save the message instance to the database
user = get_or_create_user(db, username)
msg = models.Message(**message.dict())
msg.user = user
db.add(msg)
db.commit()
db.refresh(msg)
return msg
def get_user_chat_history(db: Session, username: str):
user = db.query(models.User).filter(models.User.username == username).first()
return user.messages if user is not None else [] |