Skip to content

Commit

Permalink
Migrate to litestar (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
Saphyel authored Oct 6, 2023
1 parent b9dec63 commit 67c7a98
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 49 deletions.
1 change: 0 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
.git/
.gitignore
.github/
/*.md
Dockerfile
.coverage
**/__pycache__/
Expand Down
10 changes: 5 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ EXPOSE $PORT

WORKDIR /app

COPY pyproject.toml /app/
COPY pyproject.toml README.md ./

RUN pip install .

COPY tasker/ /app/tasker/
COPY templates/ /app/templates/
COPY tasker/ ./tasker/
COPY templates/ ./templates/

RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app/
USER appuser

CMD uvicorn tasker.main:app --host 0.0.0.0 --port $PORT
CMD uvicorn tasker.web:app --host 0.0.0.0 --port $PORT
2 changes: 1 addition & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
- ./templates/:/app/templates/
- ./tests/:/app/tests/
- ./pyproject.toml:/app/pyproject.toml
command: uvicorn tasker.main:app --host 0.0.0.0 --port 80 --reload
command: uvicorn tasker.web:app --host 0.0.0.0 --port 80 --reload
env_file: [ .env ]
depends_on:
- db
Expand Down
21 changes: 13 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ build-backend = "setuptools.build_meta"

[project]
name = "tasker"
version = "3.0"
version = "4.0"
dynamic = ["readme"]
description = ""
license = {text = "OSL-3.0"}
authors = []
readme = "README.md"

requires-python = ">=3.10"
requires-python = ">=3.11"
dependencies = [
"pymongo<4.6",
"pydantic<1.11",
"starlite[jinja]<1.52",
"pydantic-settings<2.1",
"litestar[jinja]<2.2",
"uvicorn<0.24"
]
[project.optional-dependencies]
Expand All @@ -23,16 +24,20 @@ test = [
"pytest<7.5",
"pytest-cov<4.2",
]
[tool.setuptools.packages.find]
include = ["tasker"]
[project.scripts]
tasker = "command:main"
#[project.gui-scripts]
#tasker-ui = "gui"

[tool.setuptools.packages.find]
include = ["tasker"]
[tool.setuptools.dynamic]
#version = {attr = "tasker.VERSION"}
readme = {file = ["README.md"]}

[tool.black]
line-length = 120
target-version = ['py310']
target-version = ['py311']
include = '\.pyi?$'

[tool.mypy]
Expand Down
7 changes: 5 additions & 2 deletions tasker/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from tasker.model import TaskInput, Search, Pagination
from tasker.repository import TaskRepository
from tasker.settings import app_settings
from tasker.config import app_settings

client: MongoClient = MongoClient(app_settings.database_uri)
repository = TaskRepository(client.work)
Expand All @@ -31,13 +31,16 @@ def main():
find.add_argument("-d", "--date")
find.add_argument("-s", "--sort", default="newest")
find.add_argument("-l", "--limit", type=int, default=10)
find.add_argument("-p", "--page", type=int, default=1)

args = parser.parse_args()
if args.command == "insert":
result = repository.insert(TaskInput(date=args.date, tag=args.tag, details=args.details))
logger.warning(result)
elif args.command == "find":
data = repository.find(Search(tag=args.tag, date=args.date), Pagination(limit=args.limit, sort=args.sort))
data = repository.find(
Search(tag=args.tag, date=args.date), Pagination(limit=args.limit, sort=args.sort, page=args.page)
)
[logger.warning(item.json()) for item in data.result]

else:
Expand Down
2 changes: 1 addition & 1 deletion tasker/settings.py → tasker/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseSettings
from pydantic_settings import BaseSettings


class AppSettings(BaseSettings):
Expand Down
36 changes: 14 additions & 22 deletions tasker/controllers.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
import contextlib

from starlite import (
Controller,
get,
post,
Router,
NotAuthorizedException,
Template,
Redirect,
Body,
RequestEncodingType,
Provide,
Request,
)
from litestar import Controller, get, post, Router, Request
from litestar.di import Provide
from litestar.enums import RequestEncodingType
from litestar.exceptions import NotAuthorizedException
from litestar.params import Body
from litestar.response import Template, Redirect

from tasker.config import app_settings
from tasker.model import TaskInput, Search, Pagination, SortEnum
from tasker.repository import TaskRepository, task_repository
from tasker.settings import app_settings


class TasksViewController(Controller):
Expand All @@ -33,10 +26,10 @@ async def index(
sort: str = SortEnum.newest,
) -> Template:
if not app_settings.token == token:
raise NotAuthorizedException
raise NotAuthorizedException()

return Template(
name="index.html",
template_name="index.html",
context={
"token": token,
"data": repository.find(Search(tag=tag), Pagination(limit=limit, page=page, sort=sort)),
Expand All @@ -46,11 +39,11 @@ async def index(
@get(path="/add")
async def add(self, token: str) -> Template:
if not app_settings.token == token:
raise NotAuthorizedException
raise NotAuthorizedException()

return Template(name="task.html", context={"token": token})
return Template(template_name="task.html", context={"token": token})

@post(path="/add", status_code=301)
@post(path="/add")
async def new(
self,
repository: TaskRepository,
Expand All @@ -59,12 +52,11 @@ async def new(
form: TaskInput | None = Body(media_type=RequestEncodingType.URL_ENCODED),
) -> Redirect:
if not app_settings.token == token:
raise NotAuthorizedException
raise NotAuthorizedException()

if not form:
request.logger.info(request.headers.dict()["content-type"])
form = TaskInput(**await request.form())

repository.insert(form)
return Redirect(path=f"/?token={token}")

Expand All @@ -80,5 +72,5 @@ async def health_check(repository: TaskRepository) -> str:
view_router = Router(
path="",
route_handlers=[TasksViewController, health_check],
dependencies={"repository": Provide(task_repository)},
dependencies={"repository": Provide(task_repository, sync_to_thread=False)},
)
8 changes: 4 additions & 4 deletions tasker/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class Model(BaseModel):
class Config:
anystr_strip_whitespace = True
str_strip_whitespace = True


class TaskInput(Model):
Expand All @@ -23,8 +23,8 @@ class TaskOutput(Model):


class Search(Model):
date: datetime | None
tag: str | None
tag: str | None = None
date: datetime | None = None


class SortEnum(str, Enum):
Expand All @@ -36,7 +36,7 @@ class Pagination(Model):
limit: int
sort: SortEnum
page: int = 1
total: int | None
total: int | None = None


class Result(Model):
Expand Down
2 changes: 1 addition & 1 deletion tasker/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pymongo.database import Database

from tasker.model import TaskInput, Pagination, Search, SortEnum, Result, TaskOutput
from tasker.settings import app_settings
from tasker.config import app_settings


class TaskRepository:
Expand Down
11 changes: 7 additions & 4 deletions tasker/main.py → tasker/web.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from pathlib import Path

from starlite import Starlite, CompressionConfig, LoggingConfig, TemplateConfig, Provide
from starlite.contrib.jinja import JinjaTemplateEngine
from starlite.middleware import LoggingMiddlewareConfig
from litestar import Litestar
from litestar.config.compression import CompressionConfig
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.logging.config import LoggingConfig
from litestar.middleware.logging import LoggingMiddlewareConfig
from litestar.template import TemplateConfig

from tasker.controllers import view_router

logging_middleware_config = LoggingMiddlewareConfig()

app = Starlite(
app = Litestar(
route_handlers=[view_router],
openapi_config=None,
logging_config=LoggingConfig(),
Expand Down

0 comments on commit 67c7a98

Please sign in to comment.