From ec11e35fceec6ab499518c7f09d3593a7154a66c Mon Sep 17 00:00:00 2001 From: odrling Date: Tue, 15 Oct 2024 03:50:05 +0200 Subject: [PATCH] define a default serializer to handle dataclasses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit so the generated code doesn’t just crash when used --- src/mahou/templates/aiohttp_client.py.jinja | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/mahou/templates/aiohttp_client.py.jinja b/src/mahou/templates/aiohttp_client.py.jinja index da24813..e37c537 100644 --- a/src/mahou/templates/aiohttp_client.py.jinja +++ b/src/mahou/templates/aiohttp_client.py.jinja @@ -3,6 +3,9 @@ from dataclasses import dataclass from enum import Enum from typing import {{need_typing | map('capitalize') | join(', ')}}{% if need_typing %}, {% endif %}Any, Literal, TypeGuard +import dataclasses +import json + import aiohttp from aiohttp.typedefs import Query from yarl import QueryVariable, SimpleQuery @@ -63,6 +66,18 @@ def prep_serialization(d: dict[str, Any]) -> Query: if v is not None} +class JsonDataclassEncoder(json.JSONEncoder): + + def default(self, o: Any): + if dataclasses.is_dataclass(o): + return dataclasses.as_dict + return super().default(o) + + +def default_json_serializer(o: Any) -> str: + return json.dumps(o, cls=JsonDataclassEncoder) + + {% for module_name, operations in modules.items() %} class {{module_name.capitalize()}}Module(): def __init__(self, session: 'ClientSession', server_url: str): @@ -158,6 +173,6 @@ class ClientSession(aiohttp.ClientSession): {% endfor %} {% for server in servers %} -def get{% if server.name %}_{{server.name}}{% endif %}_session(server_url: str, *args, **kwargs) -> ClientSession: - return ClientSession(server_url, *args, **kwargs) +def get{% if server.name %}_{{server.name}}{% endif %}_session(server_url: str, *args, json_serializer=default_json_serializer, **kwargs) -> ClientSession: + return ClientSession(server_url, *args, json_serializer=json_serializer, **kwargs) {% endfor %}