-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
74 lines (59 loc) · 2.31 KB
/
models.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
72
73
74
import secrets
from pydantic import BaseModel, Field
from datetime import datetime, timedelta
from typing import Union
# == HTTP MODELS == #
class ShortenBody(BaseModel):
source: str
length: int = Field(description="The length of the shortened output.", lt=10240, gt=3)
secret: str
expire: int = Field(description="After how many seconds to delete the shortened URL")
# == SQL MODELS == #
class Shortened:
__schema__ = {"source": str, "serve": str, "expire": datetime, "uses": int, "token": str}
def __init__(self, source: str, serve: str, expire: Union[datetime, str], uses: int, token: str, connection):
self.source = source
self.serve = serve
self.expire = expire
self.uses = uses
if isinstance(self.expire, str):
self.expire: datetime = self.parse_date(self.expire)
self.connection = connection
self.token = token
@classmethod
def parse_date(cls, datestring: str):
try:
return datetime.fromisoformat(datestring)
except (ValueError, TypeError, Exception):
return datetime.max
@classmethod
def calculate_offset(cls, offset: int):
try:
return datetime.utcnow() + timedelta(seconds=offset)
except (ValueError, TypeError, Exception):
return datetime.max
@property
def can_serve(self) -> bool:
"""A boolean indicating if the current URL can be served (I.E. not expired)."""
return datetime.utcnow() < self.expire
async def create(self, code: str):
token = secrets.token_hex(64)
args = (self.source, code, self.expire.isoformat(), token)
self.token = token
await self.connection.execute(
"""
INSERT INTO short (source, serve, expire, token)
VALUES (?, ?, ?, ?);
""",
args,
)
await self.connection.commit()
return self
@classmethod
async def get(cls, *, key: str = "source", value, connection):
args = (key, value)
async with connection.execute("SELECT source, serve, expire, uses FROM short WHERE ?=?", args) as cursor:
row = await cursor.fetchone()
if not row:
raise ValueError("No row matching query.")
return cls(*row, connection=connection)