request.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import abc
  2. from dataclasses import dataclass
  3. from dataclasses_json import dataclass_json
  4. from datetime import datetime
  5. from typing import List, Mapping, Optional, TypeVar, Type
  6. import lc.config as c
  7. T = TypeVar("T")
  8. class Request(metaclass=abc.ABCMeta):
  9. @classmethod
  10. @abc.abstractmethod
  11. def from_form(cls: Type[T], form: Mapping[str, str]) -> T:
  12. pass
  13. # technically this gets added by dataclass_json, but mypy isn't
  14. # aware of it, so it's going to get declared here as though it
  15. # weren't abstract and then dataclass_json will add it
  16. @classmethod
  17. def from_json(cls: Type[T], json: bytes) -> T:
  18. pass
  19. @dataclass_json
  20. @dataclass
  21. class User(Request):
  22. name: str
  23. password: str
  24. @classmethod
  25. def from_form(cls, form: Mapping[str, str]):
  26. return cls(name=form["username"], password=form["password"],)
  27. def to_token(self) -> str:
  28. return c.serializer.dumps({"name": self.name, "password": self.password,})
  29. @dataclass_json
  30. @dataclass
  31. class Link(Request):
  32. url: str
  33. name: str
  34. description: str
  35. private: bool
  36. tags: List[str]
  37. created: Optional[datetime] = None
  38. @classmethod
  39. def from_form(cls, form: Mapping[str, str]):
  40. return cls(
  41. url=form["url"],
  42. name=form["name"],
  43. description=form["description"],
  44. private="private" in form,
  45. tags=form["tags"].split(),
  46. )