Skip to content

Commit

Permalink
Merge branch 'main' into exception-usage-docs
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn authored Oct 22, 2024
2 parents 6d8f7b7 + 5255ec3 commit 883da56
Show file tree
Hide file tree
Showing 16 changed files with 211 additions and 139 deletions.
9 changes: 9 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -1877,6 +1877,15 @@
"contributions": [
"code"
]
},
{
"login": "mohammedbabelly20",
"name": "Mohammed Babelly",
"avatar_url": "https://avatars.githubusercontent.com/u/104768048?v=4",
"profile": "https://github.com/mohammedbabelly20",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,9 @@ see [the contribution guide](CONTRIBUTING.rst).
<td align="center" valign="top" width="14.28%"><a href="https://github.com/FarhanAliRaza"><img src="https://avatars.githubusercontent.com/u/62690310?v=4?s=100" width="100px;" alt="Farhan Ali Raza"/><br /><sub><b>Farhan Ali Raza</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=FarhanAliRaza" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/pogopaule"><img src="https://avatars.githubusercontent.com/u/576949?v=4?s=100" width="100px;" alt="Fabian"/><br /><sub><b>Fabian</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=pogopaule" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/mohammedbabelly20"><img src="https://avatars.githubusercontent.com/u/104768048?v=4?s=100" width="100px;" alt="Mohammed Babelly"/><br /><sub><b>Mohammed Babelly</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=mohammedbabelly20" title="Code">💻</a></td>
</tr>
</tbody>
</table>

Expand Down
34 changes: 13 additions & 21 deletions docs/examples/middleware/base.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,24 @@
from time import time
from typing import TYPE_CHECKING, Dict
import time
from typing import Dict

from litestar import Litestar, get, websocket
from litestar import Litestar, WebSocket, get, websocket
from litestar.datastructures import MutableScopeHeaders
from litestar.enums import ScopeType
from litestar.middleware import AbstractMiddleware

if TYPE_CHECKING:
from litestar import WebSocket
from litestar.types import Message, Receive, Scope, Send
from litestar.types import Message, Receive, Scope, Send


class MyMiddleware(AbstractMiddleware):
scopes = {ScopeType.HTTP}
exclude = ["first_path", "second_path"]
exclude_opt_key = "exclude_from_middleware"
exclude_opt_key = "exclude_from_my_middleware"

async def __call__(
self,
scope: "Scope",
receive: "Receive",
send: "Send",
) -> None:
start_time = time()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
start_time = time.monotonic()

async def send_wrapper(message: "Message") -> None:
if message["type"] == "http.response.start":
process_time = time() - start_time
process_time = time.monotonic() - start_time
headers = MutableScopeHeaders.from_message(message=message)
headers["X-Process-Time"] = str(process_time)
await send(message)
Expand All @@ -35,12 +27,12 @@ async def send_wrapper(message: "Message") -> None:


@websocket("/my-websocket")
async def websocket_handler(socket: "WebSocket") -> None:
async def websocket_handler(socket: WebSocket) -> None:
"""
Websocket handler - is excluded because the middleware scopes includes 'ScopeType.HTTP'
"""
await socket.accept()
await socket.send_json({"hello websocket"})
await socket.send_json({"hello": "websocket"})
await socket.close()


Expand All @@ -56,10 +48,10 @@ def second_handler() -> Dict[str, str]:
return {"hello": "second"}


@get("/third_path", exclude_from_middleware=True, sync_to_thread=False)
@get("/third_path", exclude_from_my_middleware=True, sync_to_thread=False)
def third_handler() -> Dict[str, str]:
"""Handler is excluded due to the opt key 'exclude_from_middleware' matching the middleware 'exclude_opt_key'."""
return {"hello": "second"}
"""Handler is excluded due to the opt key 'exclude_from_my_middleware' matching the middleware 'exclude_opt_key'."""
return {"hello": "third"}


@get("/greet", sync_to_thread=False)
Expand Down
12 changes: 6 additions & 6 deletions docs/reference/types.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
types
=====

.. py:currentmodule:: litestar.types
.. module:: litestar.types



Expand Down Expand Up @@ -58,15 +58,15 @@ ASGI Application Parameters
ASGI Scopes
~~~~~~~~~~~~

.. autodata:: litestar.types.ASGIVersion
.. autoclass:: litestar.types.ASGIVersion

.. autodata:: litestar.types.BaseScope
.. autoclass:: litestar.types.BaseScope

.. autodata:: litestar.types.HTTPScope
.. autoclass:: litestar.types.HTTPScope

.. autodata:: litestar.types.LifeSpanScope
.. autoclass:: litestar.types.LifeSpanScope

.. autodata:: litestar.types.WebSocketScope
.. autoclass:: litestar.types.WebSocketScope


ASGI Events
Expand Down
55 changes: 29 additions & 26 deletions docs/usage/htmx.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
HTMX
====

Litestar HTMX integration.
Litestar `HTMX <https://htmx.org>`_ integration.

HTMX is a JavaScript library that gives you access to AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, using attributes, so you can build modern user interfaces with the simplicity and power of hypertext.

This section assumes that you have prior knowledge of HTMX.
If you want to learn HTMX, we recommend consulting their `official tutorial <https://htmx.org/docs>`_.

HTMXRequest
------------
Expand All @@ -24,11 +29,8 @@ HTMX client.
@get(path="/form")
def get_form(request: HTMXRequest) -> Template:
htmx = request.htmx # if true will return HTMXDetails class object
if htmx:
print(htmx.current_url)
# OR
if request.htmx:
if request.htmx: # if request has "HX-Request" header, then
print(request.htmx) # HTMXDetails instance
print(request.htmx.current_url)
return HTMXTemplate(template_name="partial.html", context=context, push_url="/form")
Expand All @@ -43,7 +45,7 @@ HTMX client.
),
)
See :class:`HTMXDetails <litestar.contrib.htmx.request.HTMXDetails>` for a full list of
See :class:`~litestar.contrib.htmx.request.HTMXDetails` for a full list of
available properties.


Expand All @@ -54,8 +56,8 @@ HTMX Response Classes
HTMXTemplate Response Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The most common use-case for `htmx` to render an html page or html snippet. Litestar makes this easy by providing
an :class:`HTMXTemplate <litestar.contrib.htmx.response.HTMXTemplate>` response:
The most common use-case for HTMX to render an html page or html snippet. Litestar makes this easy by providing
an :class:`~litestar.contrib.htmx.response.HTMXTemplate` response:

.. code-block:: python
Expand Down Expand Up @@ -89,10 +91,10 @@ an :class:`HTMXTemplate <litestar.contrib.htmx.response.HTMXTemplate>` response:
HTMX provides two types of responses - one that doesn't allow changes to the DOM and one that does.
Litestar supports both of these:

1 - Responses that don't make any changes to DOM.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 - Responses that don't make any changes to DOM
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use :class:`HXStopPolling <litestar.contrib.htmx.response.HXStopPolling>` to stop polling for a response.
Use :class:`~litestar.contrib.htmx.response.HXStopPolling` to stop polling for a response.

.. code-block:: python
Expand All @@ -101,7 +103,7 @@ Use :class:`HXStopPolling <litestar.contrib.htmx.response.HXStopPolling>` to sto
...
return HXStopPolling()
Use :class:`ClientRedirect <litestar.contrib.htmx.response.ClientRedirect>` to redirect with a page reload.
Use :class:`~litestar.contrib.htmx.response.ClientRedirect` to redirect with a page reload.

.. code-block:: python
Expand All @@ -110,7 +112,7 @@ Use :class:`ClientRedirect <litestar.contrib.htmx.response.ClientRedirect>` to
...
return ClientRedirect(redirect_to="/contact-us")
Use :class:`ClientRefresh <litestar.contrib.htmx.response.ClientRefresh>` to force a full page refresh.
Use :class:`~litestar.contrib.htmx.response.ClientRefresh` to force a full page refresh.

.. code-block:: python
Expand All @@ -119,12 +121,12 @@ Use :class:`ClientRefresh <litestar.contrib.htmx.response.ClientRefresh>` to fo
...
return ClientRefresh()
2 - Responses that may change DOM.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 - Responses that may change DOM
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use :class:`HXLocation <litestar.contrib.htmx.response.HXLocation>` to redirect to a new location without page reload.
Use :class:`~litestar.contrib.htmx.response.HXLocation` to redirect to a new location without page reload.

- Note: this class provides the ability to change ``target``, ``swapping`` method, the sent ``values``, and the ``headers``.)
.. note:: This class provides the ability to change ``target``, ``swapping`` method, the sent ``values``, and the ``headers``.

.. code-block:: python
Expand All @@ -138,13 +140,13 @@ Use :class:`HXLocation <litestar.contrib.htmx.response.HXLocation>` to redirect
event, # an event that "triggered" the request.
target="#target", # element id to target to.
swap="outerHTML", # swapping method to use.
hx_headers={"attr": "val"}, # headers to pass to htmx.
hx_headers={"attr": "val"}, # headers to pass to HTMX.
values={"val": "one"},
) # values to submit with response.
Use :class:`PushUrl <litestar.contrib.htmx.response.PushUrl>` to carry a response and push a url to the browser, optionally updating the `history` stack.
Use :class:`~litestar.contrib.htmx.response.PushUrl` to carry a response and push a url to the browser, optionally updating the ``history`` stack.

- Note: If the value for ``push_url`` is set to ``False`` it will prevent updating browser history.
.. note:: If the value for ``push_url`` is set to ``False`` it will prevent updating browser history.

.. code-block:: python
Expand All @@ -153,8 +155,9 @@ Use :class:`PushUrl <litestar.contrib.htmx.response.PushUrl>` to carry a respons
...
return PushUrl(content="Success!", push_url="/about")
Use :class:`ReplaceUrl <litestar.contrib.htmx.response.ReplaceUrl>` to carry a response and replace the url in the browser's ``location`` bar.
- Note: If the value to ``replace_url`` is set to ``False`` it will prevent it updating the browser location bar.
Use :class:`~litestar.contrib.htmx.response.ReplaceUrl` to carry a response and replace the url in the browser's ``location`` bar.

.. note:: If the value to ``replace_url`` is set to ``False`` it will prevent updating the browser's location.

.. code-block:: python
Expand All @@ -163,7 +166,7 @@ Use :class:`ReplaceUrl <litestar.contrib.htmx.response.ReplaceUrl>` to carry a r
...
return ReplaceUrl(content="Success!", replace_url="/contact-us")
Use :class:`Reswap <litestar.contrib.htmx.response.Reswap>` to carry a response perhaps a swap
Use :class:`~litestar.contrib.htmx.response.Reswap` to carry a response with a possible swap.

.. code-block:: python
Expand All @@ -172,7 +175,7 @@ Use :class:`Reswap <litestar.contrib.htmx.response.Reswap>` to carry a response
...
return Reswap(content="Success!", method="beforebegin")
Use :class:`Retarget <litestar.contrib.htmx.response.Retarget>` to carry a response and change the target element.
Use :class:`~litestar.contrib.htmx.response.Retarget` to carry a response and change the target element.

.. code-block:: python
Expand All @@ -181,7 +184,7 @@ Use :class:`Retarget <litestar.contrib.htmx.response.Retarget>` to carry a respo
...
return Retarget(content="Success!", target="#new-target")
Use :class:`TriggerEvent <litestar.contrib.htmx.response.TriggerEvent>` to carry a response and trigger an event.
Use :class:`~litestar.contrib.htmx.response.TriggerEvent` to carry a response and trigger an event.

.. code-block:: python
Expand Down
10 changes: 5 additions & 5 deletions docs/usage/lifecycle-hooks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Before Request
--------------

The ``before_request`` hook runs immediately before calling the route handler function. It
can be any callable accepting a :class:`Request <.connection.Request>` as its first parameter
can be any callable accepting a :class:`~litestar.connection.Request` as its first parameter
and returns either ``None`` or a value that can be used in a response.
If a value is returned, the router handler for this request will be bypassed.

Expand All @@ -34,7 +34,7 @@ After Request
-------------

The ``after_request`` hook runs after the route handler returned and the response object
has been resolved. It can be any callable which takes a :class:`Response <.response.Response>`
has been resolved. It can be any callable which takes a :class:`~litestar.response.Response`
instance as its first parameter, and returns a ``Response`` instance. The ``Response``
instance returned does not necessarily have to be the one that was received.

Expand All @@ -48,7 +48,7 @@ After Response
--------------

The ``after_response`` hook runs after the response has been returned by the server.
It can be any callable accepting a :class:`Request <.connection.Request>` as its first parameter
It can be any callable accepting a :class:`~litestar.connection.Request` as its first parameter
and does not return any value.

This hook is meant for data post-processing, transmission of data to third party
Expand All @@ -60,8 +60,8 @@ services, gathering of metrics, etc.

.. note::

Since the request has already been returned by the time the `after_response` is called,
the updated state of `COUNTER` is not reflected in the response.
Since the request has already been returned by the time the ``after_response`` is called,
the updated state of ``COUNTER`` is not reflected in the response.


Layered hooks
Expand Down
2 changes: 2 additions & 0 deletions docs/usage/logging.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.. _logging-usage:

Logging
=======

Expand Down
Loading

0 comments on commit 883da56

Please sign in to comment.