generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathfollows.py
More file actions
51 lines (42 loc) · 1.72 KB
/
follows.py
File metadata and controls
51 lines (42 loc) · 1.72 KB
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
from typing import List
from data.connection import db_cursor
from data.users import User
from psycopg2.errors import UniqueViolation
def follow(follower: User, followee: User):
with db_cursor() as cur:
try:
cur.execute(
"INSERT INTO follows (follower, followee) VALUES (%(follower_id)s, %(followee_id)s)",
dict(
follower_id=follower.id,
followee_id=followee.id,
),
)
except UniqueViolation:
# Already following - treat as idempotent request.
pass
# do the opposite for unfollow
def unfollow(follower: User, followee: User):
with db_cursor() as cur:
cur.execute(
"DELETE FROM follows WHERE follower = %(follower_id)s AND followee = %(followee_id)s",
dict(follower_id=follower.id, followee_id=followee.id)
)
def get_followed_usernames(follower: User) -> List[str]:
"""get_followed_usernames returns a list of usernames followee follows."""
with db_cursor() as cur:
cur.execute(
"SELECT users.username FROM follows INNER JOIN users ON follows.followee = users.id WHERE follower = %s",
(follower.id,),
)
rows = cur.fetchall()
return [row[0] for row in rows]
def get_inverse_followed_usernames(followee: User) -> List[str]:
"""get_followed_usernames returns a list of usernames followed by follower."""
with db_cursor() as cur:
cur.execute(
"SELECT users.username FROM follows INNER JOIN users ON follows.follower = users.id WHERE followee = %s",
(followee.id,),
)
rows = cur.fetchall()
return [row[0] for row in rows]