-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.py
71 lines (58 loc) · 1.94 KB
/
crud.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
from sqlalchemy import func
from sqlalchemy.orm import Session
from database import User,Users,Post,UserFeedback,Upvote
# Create a new user
# Retrieve a user by email
def get_user_by_email(db: Session, email: str):
return db.query(Users).filter(Users.email == email).first()
def get_admin_user_by_email(db: Session, email: str):
return db.query(User).filter(User.email == email).first()
# Update user's OTP by email
def update_user_otp(db: Session, email: str, new_otp: str):
user = get_user_by_email(db, email)
if user:
user.otp = new_otp
db.commit()
return user
# Delete a user by email
def delete_admin_user_by_email(db: Session, email: str):
user = get_admin_user_by_email(db, email)
if user:
db.delete(user)
db.commit()
return user
# Delete a user by email
def delete_user_by_email(db: Session, email: str):
user = get_user_by_email(db, email)
if user:
db.delete(user)
db.commit()
return user
def get_posts_by_city(db: Session):
posts_by_city = (
db.query(Post.city, func.count(Post.id))
.group_by(Post.city)
.all()
)
return posts_by_city
def get_average_rating(db: Session):
average_rating = db.query(func.avg(UserFeedback.rating)).scalar()
return average_rating
def get_most_active_users(db: Session):
most_active_users = (
db.query(Users.email, func.count(Post.id))
.join(Post, Users.id == Post.author_id)
.group_by(Users.email)
.order_by(func.count(Post.id).desc())
.limit(5)
.all()
)
return most_active_users
def get_upvotes_per_post(db: Session):
upvotes_per_post = (
db.query(Post.id, Post.title, func.count(Upvote.id))
.outerjoin(Upvote, Post.id == Upvote.post_id)
.group_by(Post.id, Post.title)
.all()
)
return upvotes_per_post