Skip to content

Commit

Permalink
refactor: fix typing error with pyright
Browse files Browse the repository at this point in the history
  • Loading branch information
trim21 committed Feb 18, 2025
1 parent 646d063 commit ed54ab5
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 18 deletions.
16 changes: 15 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ dev = [
'asyncpg-stubs ==0.30.0',
'types-pyyaml ==6.0.12.20241230',
'google-re2-stubs ==0.1.1',
"types-redis>=4.6.0.20241004",
]

[tool.uv]
package = false
required-environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'win32' and platform_machine == 'x86_64'",

]

[tool.black]
Expand Down Expand Up @@ -144,3 +144,17 @@ exclude = ['tests']

[tool.pytest.ini_options]
python_files = ['tests/**.py', 'test_*.py', '*_test.py']

[tool.pyright]
root = '.'
ignore = ['./tests/']
# include = ['./transmission_rpc/']
# ignore = ['./tests/', './docs/']
pythonVersion = '3.10'
pythonPlatform = 'Linux'
typeCheckingMode = "strict"
# reportUnnecessaryComparison = false
reportUnknownVariableType = false
reportUnknownMemberType = false
reportUnnecessaryIsInstance = false
reportPrivateUsage = false
2 changes: 1 addition & 1 deletion server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def internal_error_handler(req: Request, exc: Exception) -> Response[Any]:

async def startup_fetch_missing_users() -> None:
logger.info("fetch missing users")
s = set()
s: set[int | None] = set()

for u1, u2 in await pg.fetch("select from_user_id, wiki_user_id from subject_patch"):
s.add(u1)
Expand Down
2 changes: 1 addition & 1 deletion server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

HEADER_KEY_API = "x-api-token"

SUPER_USERS = {}
SUPER_USERS: dict[str, dict[str, int]] = {}

for key in os.environ:
if not key.startswith("SUPER_USER_TOKEN_"):
Expand Down
15 changes: 7 additions & 8 deletions server/contrib.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,8 @@ async def suggest_api(
res.raise_for_status()
original_wiki = res.json()

original = {}

changed = {}
original: dict[str, Any] = {}
changed: dict[str, Any] = {}

for key in ["name", "infobox", "summary"]:
before = original_wiki[key]
Expand Down Expand Up @@ -199,9 +198,9 @@ async def suggest_api_from_partial(
res.raise_for_status()
original_wiki = res.json()

original = {}
original: dict[str, Any] = {}

changed = {}
changed: dict[str, Any] = {}

for key in ["name", "infobox", "summary", "nsfw"]:
before = original_wiki[key]
Expand Down Expand Up @@ -353,7 +352,7 @@ async def _(

patch = SubjectPatch.from_dict(p)

changed = {}
changed: dict[str, Any] = {}

if patch.from_user_id != request.auth.user_id:
raise PermissionDeniedException()
Expand Down Expand Up @@ -494,7 +493,7 @@ async def creat_episode_patch(

keys = ["airdate", "name", "name_cn", "duration", "description"]

changed = {}
changed: dict[str, Any] = {}

for key in keys:
if original_wiki[key] != getattr(data, key):
Expand All @@ -505,7 +504,7 @@ async def creat_episode_patch(

reason = data.reason.strip()
if not reason:
reasons = []
reasons: list[str] = []
for key in changed:
if original_wiki[key]:
reasons.append(f"修改{patch_keys[key]}")
Expand Down
23 changes: 16 additions & 7 deletions server/tmpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from jinja2.runtime import Context
from litestar import Request
from markupsafe import Markup
from multidict import MultiDict

from server.config import DEV, PROJECT_PATH, TURNSTILE_SITE_KEY, UTC

Expand All @@ -21,9 +22,13 @@
auto_reload=DEV,
)

engine.globals["TURNSTILE_SITE_KEY"] = TURNSTILE_SITE_KEY
engine.globals["min"] = min
engine.globals["max"] = max

engine_globals: dict[str, Any] = engine.globals
engine_filters: dict[str, Any] = engine.filters

engine_globals["TURNSTILE_SITE_KEY"] = TURNSTILE_SITE_KEY
engine_globals["min"] = min
engine_globals["max"] = max

P = typing.ParamSpec("P")
T = typing.TypeVar("T")
Expand All @@ -41,11 +46,15 @@ def add_filter(s: str | Callable[P, T]) -> Any:
def real_wrapper(name: str, fn: Callable[P, T]) -> Callable[P, T]:
if name in engine.filters:
raise ValueError(f"filter '{name}' already exists")
engine.filters[name] = fn
engine_filters[name] = fn
return fn

if isinstance(s, str):
return lambda fn: real_wrapper(s, fn)

def inner(fn: Callable[P, T]):

Check failure on line 54 in server/tmpl.py

View workflow job for this annotation

GitHub Actions / mypy

Function is missing a return type annotation
return real_wrapper(s, fn)

return inner

return real_wrapper(s.__name__, s)

Expand All @@ -54,7 +63,7 @@ def add_global_function(fn: Callable[P, T]) -> Callable[P, T]:
name = fn.__name__
if name in engine.globals:
raise ValueError(f"filter '{name}' already exists")
engine.globals[name] = fn
engine_globals[name] = fn
return fn


Expand Down Expand Up @@ -134,7 +143,7 @@ def to_user_local_time(ctx: Context, dt: datetime) -> str:
@pass_context
def replace_url_query(ctx: Context, **kwargs: Any) -> str:
req: Request[None, None, Any] = ctx["request"]
q = req.url.query_params.copy()
q: MultiDict[Any] = req.url.query_params.copy()
q.update(kwargs)
return req.url.path + "?" + urlencode(q)

Expand Down
Loading

0 comments on commit ed54ab5

Please sign in to comment.