File size: 1,881 Bytes
57ea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# https://redis.io/docs/clients/python/
from redis import Redis
from dotenv import load_dotenv
from uuid import uuid4

load_dotenv()
import os
import json
from redis.commands.json.path import Path

from typing import TypedDict, List, Tuple, Optional


class User(TypedDict):
    username: str
    uid: str


class Chat(TypedDict):
    patient: str
    messages: List[Tuple[str, str]]


def get_client() -> Redis:
    client = Redis(
        host=os.environ["REDIS_HOST"],
        port=os.environ["REDIS_PORT"],
        decode_responses=True,
    )
    return client


def create_user(client: Redis, user: User):
    maybe_user = get_user_by_username(client, user["username"])
    if not maybe_user:
        uid = uuid4()
        user["uid"] = str(uid)
        client.json().set(f"user:by-uid:{uid}", "$", user, nx=True)
        client.set(f"user:uuid:by-username:{user['username']}", str(uid), nx=True)
        client.json().set(f"chats:by-user-uid:{uid}", "$", [])
    else:
        print(f"User already existed with username={user['username']}")


def get_user_by_username(client: Redis, username: str) -> Optional[User]:
    uid = client.get(f"user:uuid:by-username:{username}")
    user = client.json().get(f"user:by-uid:{uid}")
    return user


def get_user_chat_by_uid(client: Redis, uid: str) -> List[Chat]:
    chats = client.json().get(f"chats:by-user-uid:{uid}")
    return chats


def add_chat_by_uid(client: Redis, chat: Chat, uid: str):
    client.json().arrappend(f"chats:by-user-uid:{uid}", "$", chat)


# if __name__ == "__main__":

#     client = get_client()
#     user = User(username="foo")
#     chat = Chat(patient="foo", messages=[("a", "b"), ("c", "d")])

#     create_user(client, user)
#     user = get_user_by_username(client, user['username'])
#     add_chat_by_uid(client, chat, "1")
#     chats = get_user_chat_by_uid(client, "1")
#     print(chats)