-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
72 lines (56 loc) · 2.2 KB
/
db.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from fastapi import Depends
from fastapi import HTTPException
from fastapi import status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from models import UserFile
from models import UserIn
from models import UserOut
from models import UserTable
def get_user(db: Session, username: str):
return db.query(UserTable).filter(UserTable.username == username).first()
""" def create_user(db: Session, user: UserIn):
hashed_password = get_password_hash(user.password)
db_user = UserTable(
username=user.username,
full_name=user.full_name,
email=user.email,
hashed_password=hashed_password,
disabled=user.disabled
)
db.add(db_user)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(status_code=400, detail="Username or Email already registered")
return db_user.to_dict() """
def add_file_to_user(db: Session, user_id: str, file_id: str):
# Check if the file with the provided file_id exists in the database
file = db.query(UserFile).filter(UserFile.file_id == file_id).first()
if not file:
raise HTTPException(status_code=404, detail="File not found")
# Check if the user has already been assigned the file
user_file = (db.query(UserFile).filter(
UserFile.user_id == user_id, UserFile.file_id == file_id).first())
if user_file:
raise HTTPException(status_code=400,
detail="File already assigned to the user")
db_user_file = UserFile(user_id=user_id, file_id=file_id)
db.add(db_user_file)
db.commit()
return {"detail": "File added to user"}
def get_user_files(db: Session, user_id: str):
user_files = db.query(UserFile).filter(UserFile.user_id == user_id).all()
return {"file_ids": [uf.file_id for uf in user_files]}
def create_file_db(db: Session, user_id: int, file_name: str):
# Create the File
new_file = UserFile(file_name=file_name)
db.add(new_file)
db.commit()
# Get the file_id of the newly created file
file_id = new_file.file_id
# Assign the File to a User
user_file = UserFile(user_id=user_id, file_id=file_id)
db.add(user_file)
db.commit()