File size: 2,108 Bytes
57ea903
 
 
 
 
ca72837
57ea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9e1876
e5bbb18
 
57ea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca72837
 
 
57ea903
 
 
 
e5bbb18
57ea903
 
 
 
 
 
 
c9e1876
 
 
 
 
 
e5bbb18
c9e1876
 
 
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
73
74
# https://redis.io/docs/clients/python/
from redis import Redis
from dotenv import load_dotenv
from uuid import uuid4

load_dotenv(".env")
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"],
        password=os.environ["REDIS_PASSWORD"],
        ssl=os.environ.get("REDIS_USE_SSL", "True") == "True",
        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}", "$")
    if user:
       user = user[0]
    return user


def get_user_chat_by_uid(client: Redis, uid: str) -> List[Chat]:
    chats = client.json().get(f"chats:by-user-uid:{uid}", "$")[0]
    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", uid="afa03747-a9ce-4200-964c-7816ec381fa9")
    chat = Chat(patient="foo", messages=[("a", "b"), ("c", "d")])
    create_user(client, user)
    user = get_user_by_username(client, user['username'])
    print("user", user)
    add_chat_by_uid(client, chat, user['uid'])
    chats = get_user_chat_by_uid(client, user['uid'])
    print(chats)