Skip to content

Commit

Permalink
define a default serializer to handle dataclasses
Browse files Browse the repository at this point in the history
so the generated code doesn’t just crash when used
  • Loading branch information
odrling committed Oct 15, 2024
1 parent a550570 commit ec11e35
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/mahou/templates/aiohttp_client.py.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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 %}

0 comments on commit ec11e35

Please sign in to comment.