Skip to content

Commit

Permalink
New CurrentUserContextManager
Browse files Browse the repository at this point in the history
  • Loading branch information
dmezzogori committed May 31, 2023
1 parent 2c7d311 commit 73a5810
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions kwik/database/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from . import base, mixins, session
from .current_user_context_manager import CurrentUserContextManager
from .db_context_manager import DBContextManager
from .db_context_switcher import DBContextSwitcher
24 changes: 24 additions & 0 deletions kwik/database/current_user_context_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from __future__ import annotations

from contextlib import contextmanager
from typing import TYPE_CHECKING, Generator

from kwik.database.context_vars import current_user_ctx_var

if TYPE_CHECKING:
import kwik.models


@contextmanager
def CurrentUserContextManager(user: kwik.models.User) -> Generator[None, None, None]:
"""
Context manager for the current user.
Automatically manages the current user for the CRUD operations.
"""

token = current_user_ctx_var.set(user)
try:
yield
finally:
current_user_ctx_var.reset(token)
2 changes: 1 addition & 1 deletion kwik/database/db_context_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class DBContextManager:
def __init__(self) -> None:
"""
Initialize the DBContextManager.
"""

self.db: Session | None = None
self.token: Token[Session | None] | None = None

Expand Down
7 changes: 7 additions & 0 deletions kwik/utils/enum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import annotations

import enum


def merge_str_enum(name: str, *args):
return enum.StrEnum(name, [(e, e) for arg in args for e in arg])

0 comments on commit 73a5810

Please sign in to comment.