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

Add custom encoder support to trigger_client_event() #349

Merged
merged 7 commits into from
Jul 9, 2023
Merged
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
4 changes: 4 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ Changelog

* Remove the unnecessary ``type`` attribute on the ``<script>`` tag generated by ``django_htmx_script``.

* Allow custom JSON encoders in ``trigger_client_event()``.

Thanks to Joey Lange in `PR #349 <https://github.com/adamchainz/django-htmx/pull/349>`__.

1.15.0 (2023-06-13)
-------------------

Expand Down
13 changes: 9 additions & 4 deletions docs/http.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,22 @@ Response modifying functions
``name`` is the name of the event to trigger.

``params`` specifies optional JSON-compatible parameters for the event.
Uses |DjangoJSONEncoder|__ for its extended data type support.

.. |DjangoJSONEncoder| replace:: ``DjangoJSONEncoder``
__ https://docs.djangoproject.com/en/stable/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder

``after`` selects which of the ``HX-Trigger`` headers to modify:

* ``"receive"``, the default, maps to ``HX-Trigger``
* ``"settle"`` maps to ``HX-Trigger-After-Settle``
* ``"swap"`` maps to ``HX-Trigger-After-Swap``

``encoder`` specifies the |JSONEncoder|__ class used to generate the JSON.
Defaults to |DjangoJSONEncoder|__ for its extended data type support.

.. |JSONEncoder| replace:: ``JSONEncoder``
__ https://docs.python.org/3/library/json.html#json.JSONEncoder

.. |DjangoJSONEncoder| replace:: ``DjangoJSONEncoder``
__ https://docs.djangoproject.com/en/stable/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder

Calling ``trigger_client_event`` multiple times for the same ``response`` and ``after`` will update the appropriate header, preserving existing event specifications.

For example:
Expand Down
3 changes: 2 additions & 1 deletion src/django_htmx/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def trigger_client_event(
params: dict[str, Any] | None = None,
*,
after: Literal["receive", "settle", "swap"] = "receive",
encoder: type[json.JSONEncoder] = DjangoJSONEncoder,
) -> _HttpResponse:
params = params or {}

Expand All @@ -146,6 +147,6 @@ def trigger_client_event(
else:
data = {name: params}

response[header] = json.dumps(data, cls=DjangoJSONEncoder)
response[header] = json.dumps(data, cls=encoder)

return response
31 changes: 31 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from uuid import UUID

import pytest
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.http import StreamingHttpResponse
from django.test import SimpleTestCase
Expand Down Expand Up @@ -235,3 +236,33 @@ def test_django_json_encoder(self):
response["HX-Trigger"]
== '{"showMessage": {"uuid": "12345678-1234-5678-1234-567812345678"}}'
)

def test_custom_json_encoder(self):
class Bean:
pass

class BeanEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, Bean):
return "bean"

return super().default(o)

response = HttpResponse()

trigger_client_event(
response,
"showMessage",
{
"a": UUID("{12345678-1234-5678-1234-567812345678}"),
"b": Bean(),
},
encoder=BeanEncoder,
)

assert response["HX-Trigger"] == (
'{"showMessage": {'
+ '"a": "12345678-1234-5678-1234-567812345678",'
+ ' "b": "bean"'
+ "}}"
)