-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
40 lines (28 loc) · 1.03 KB
/
Copy pathdb.py
File metadata and controls
40 lines (28 loc) · 1.03 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
import typing
import random
from pydantic import BaseModel
from pydantic import Field
class PhraseInput(BaseModel):
"""Phrase Model"""
author: str = "Anonymous"
text: str = Field(..., title='Text',
description='Text of phrase', max_length=200)
class PhraseOutput(BaseModel):
id: typing.Optional[int] = None
class Database:
def __init__(self):
self._items: typing.Dict[int, PhraseOutput] = {}
def get_random(self) -> int:
return random.choice(self._items.keys())
def get(self, id: int) -> typing.Optional[PhraseOutput]:
return self._items.get(id)
def add(self, phrase: PhraseInput) -> PhraseOutput:
id = len(self._items) + 1
phrase_out = PhraseOutput(id=id, **phrase.dict())
self._items[phrase_out.id] = phrase_out
return phrase_out
def delete(self, id: int) -> typing.Union[typing.NoReturn, None]:
if id in self._items:
del self._items[id]
else:
raise ValueError('Phrase does not exist')