Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed request context bug, silenced Ruff warnings #7

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,6 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# IDE
.vscode
43 changes: 25 additions & 18 deletions fasthx/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""FastHX: FastAPI and HTMX, the right way."""

import inspect
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
Expand All @@ -17,52 +19,54 @@ def _append_to_signature(
func: Callable[_P, _T],
*params: inspect.Parameter,
) -> Callable[_P, _T]:
"""
Appends the given parameters to the *end* of signature of the given function.
"""Appends the given parameters to the *end* of signature of the given function.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not reformat the docstring. I understand that this is probably the most common style, but starting multiline docstrings on a newline is much more readable. Also, please don't add horizontal lines after Notes, Sections and Returns.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understand. I only changed it because VS Code was going bananas, the entire files was covered in red and yellow. Most of these docstring changes are just so that I can actually read the code. I think this is because I didn't load up your ruff configs, more below.


Notes:
-----
- This method does not change the function's arguments, it only makes FastAPI's
dependency resolution system recognize inserted parameters.
- This is *not* a general purpose method, it is strongly recommended to only
append keyword-only parameters that have "unique" names that are unlikely to
be already in the function's signature.

Arguments:
---------
func: The function whose signature should be extended.
params: The parameters to add to the function's signature.

Returns:
-------
The received function with an extended `__signature__`.
"""

""" # noqa: D401
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pyproject.toml contains the linter config - I'm assuming your local development environment did not load the settings from there, otherwise there wouldn't be a linter warning here. I'll update the CI to run on PRs - that would flag your changes.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps worth putting down a contributor guideline on these things. And yeah, definitely a good idea to have CI check on these things.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, adding more docs on how to do linting and formatting locally (poethepoet tasks) would be helpful, but I think following the already existing coding and documentation pattern should be possible regardless.

Th CI check is already in place - I added it not long ago.

signature = inspect.signature(func)
func.__signature__ = signature.replace(parameters=(*signature.parameters.values(), *params)) # type: ignore[attr-defined]
return func


class HTMXRenderer(Protocol[_Tcontra]):
"""
HTMX renderer definition.
"""HTMX renderer definition.

Arguments:
---------
result: The result of the route the renderer is used on.
context: Every keyword argument the route received.
request: The request being served.

Returns:
-------
HTML string (it will be automatically converted to `HTMLResponse`) or a `Response` object.

"""

def __call__(
def __call__( # noqa: D102
self, result: _Tcontra, *, context: dict[str, Any], request: Request
) -> str | Response | Awaitable[str | Response]:
...


def get_hx_request(request: Request, hx_request: Annotated[str | None, Header()] = None) -> Request | None:
"""
FastAPI dependency that returns the current request if it is an HTMX one,
i.e. it contains an `"HX-Request: true"` header.
"""
"""FastAPI dependency that returns the current request if it is an HTMX one, i.e. it contains an `"HX-Request: true"` header."""
return request if hx_request == "true" else None


Expand All @@ -73,14 +77,15 @@ def get_hx_request(request: Request, hx_request: Annotated[str | None, Header()]
def hx(
render: HTMXRenderer[_T], *, no_data: bool = False
) -> Callable[[Callable[_P, _T | Awaitable[_T]]], Callable[_P, Awaitable[_T | Response]]]:
"""
Decorator that converts a FastAPI route's return value into HTML if the request was
"""Decorator that converts a FastAPI route's return value into HTML if the request was
an HTMX one.

Arguments:
---------
render: The render function converting the route's return value to HTML.
no_data: If set, the route will only accept HTMX requests.
"""

""" # noqa: D205, D401

def decorator(
func: Callable[_P, _T | Awaitable[_T]],
Expand Down Expand Up @@ -129,17 +134,19 @@ class Jinja:
def __call__(
self, template_name: str, *, no_data: bool = False
) -> Callable[[Callable[_P, Any | Awaitable[Any]]], Callable[_P, Awaitable[Any | Response]]]:
"""
Decorator for rendering a route's return value to HTML using the Jinja2 template
"""Decorator for rendering a route's return value to HTML using the Jinja2 template
with the given name.

Arguments:
---------
template_name: The name of the Jinja2 template to use.
no_data: If set, the route will only accept HTMX requests.
"""

def render(result: Any, *, context: dict[str, Any], request: Request) -> HTMLResponse:
return self.templates.TemplateResponse(name=template_name, request=request, context=result)
""" # noqa: D205, D401

def render(result: Any, *, context: dict[str, Any], request: Request): # type: ignore[no-untyped-def]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please restore the original return type, there'd be no need for the type ignore then.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was also an autocorrect by Ruff. I do apologise, this is my first week of writing Python, still getting familiar with the tools and patterns etc.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how this happened, but ruff shouldn't remove the return type annotation or add type: ignore comments. Static type analysis is done with mypy.

context_with_request = {"request": request, **context}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to move this logic into a _build_context(result: Any, *, route_context: dict[str, Any], request: Request) -> dict[str, Any] hook method that can be overridden by people who would also like to include the route's "context" (its resolved dependencies) in the Jinja rendering context. See issue #4

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I think you're making a mistake here, see the docs of HTMXRenderer: context is the route's context (=its resolved dependencies) in this setting, not the Jinja rendering context. Actually, the route's return value will end up being the Jinja rendering context. Again, please have a look at #4

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for explaining. I admit I didn't see #4, feel free to close this one.

return self.templates.TemplateResponse(name=template_name, context=context_with_request)

return hx(render, no_data=no_data)

Expand Down