Skip to content

Commit a761fa8

Browse files
committed
feat(json): add support for custom json parsers
1 parent c9a59f2 commit a761fa8

File tree

6 files changed

+58
-43
lines changed

6 files changed

+58
-43
lines changed

docs/examples/full_settings.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
import json
2+
13
from qlient import Settings, Client
24

35
my_settings = Settings(
46
introspect=True, # default, enable backend schema introspection
57
validate_fields=True, # default, enable query field selection validation
6-
validate_variables=True # default, enable query variable validation
8+
validate_variables=True, # default, enable query variable validation,
9+
json_dumps=json.dumps, # default, use python's builtin json.dumps for internal dumping
10+
json_loads=json.loads, # default, use python's builtin json.loads for internal loading
711
)
812

913
my_client = Client("https://...", settings=my_settings)
Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
1-
from qlient import Client
1+
from qlient import Client, Settings
22
from qlient.cache import SqliteCache
33

44
client = Client("https://...", cache=SqliteCache())
55

66
# or with custom settings
77

8+
settings = Settings(
9+
json_loads=..., # uses json.loads by default, can be overwritten to ujson.loads
10+
json_dumps=..., # and ujson.dumps
11+
)
12+
813
client = Client(
914
"https://...",
1015
cache=SqliteCache(
1116
path="/path/to/my/schema_cache.sqlite",
12-
expires_in=86400 # seconds
17+
expires_in=86400, # seconds
18+
settings=settings,
1319
)
1420
)

poetry.lock

Lines changed: 16 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "qlient"
3-
version = "0.2.0-beta"
3+
version = "0.2.1-beta"
44
description = "A fast and modern graphql client designed with simplicity in mind."
55
authors = ["Daniel Seifert <[email protected]>"]
66
maintainers = ["Daniel Seifert <[email protected]>"]

src/qlient/cache.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import collections.abc
88
import datetime
99
import errno
10-
import json
1110
import logging
1211
import os
1312
import sqlite3
@@ -18,6 +17,7 @@
1817

1918
import platformdirs
2019

20+
from qlient.settings import Settings
2121
from qlient.schema.types import RawSchema
2222

2323
logger = logging.getLogger("qlient")
@@ -120,30 +120,11 @@ class SqliteCache(Cache):
120120
LENGTH_STMT = f"SELECT COUNT(URL) AS CACHE_SIZE FROM {TABLE_NAME}" # skipcq: BAN-B608
121121
ITER_STMT = f"SELECT URL, SCHEMA FROM {TABLE_NAME}" # skipcq: BAN-B608
122122

123-
@staticmethod
124-
def _encode_schema(schema: RawSchema) -> str:
125-
"""Static method to encode the raw schema before inserting it into the database
126-
127-
:param schema: holds the raw schema
128-
:return: a base64 encoded representation of the schema
129-
"""
130-
schema_string = json.dumps(schema, ensure_ascii=False)
131-
return base64.b64encode(schema_string.encode()).decode()
132-
133-
@staticmethod
134-
def _decode_schema(encoded_schema: str) -> RawSchema:
135-
"""Static method to decode the base64 encoded schema back to the dictionary
136-
137-
:param encoded_schema: holds a base64 representation of the schema
138-
:return: a raw schema instance
139-
"""
140-
decoded_raw_schema = base64.b64decode(encoded_schema.encode()).decode()
141-
return json.loads(decoded_raw_schema)
142-
143123
def __init__(
144124
self,
145125
path: Optional[str] = None,
146-
expires_in: Union[int, datetime.timedelta] = ONE_HOUR
126+
expires_in: Union[int, datetime.timedelta] = ONE_HOUR,
127+
settings: Optional[Settings] = None,
147128
):
148129
"""Initialize a new sqlite cache
149130
@@ -156,6 +137,7 @@ def __init__(
156137
+ "Please use qlient.cache.InMemoryCache()."
157138
)
158139

140+
self.settings: Settings = settings if settings is not None else Settings()
159141
self.path: str = path or _get_default_sqlite_cache_file()
160142

161143
if isinstance(expires_in, int):
@@ -186,6 +168,24 @@ def create_cache_table_if_not_exists(self):
186168
cursor.execute(self.TABLE_STMT)
187169
connection.commit()
188170

171+
def _encode_schema(self, schema: RawSchema) -> str:
172+
"""Static method to encode the raw schema before inserting it into the database
173+
174+
:param schema: holds the raw schema
175+
:return: a base64 encoded representation of the schema
176+
"""
177+
schema_string = self.settings.json_dumps(schema, ensure_ascii=False)
178+
return base64.b64encode(schema_string.encode()).decode()
179+
180+
def _decode_schema(self, encoded_schema: str) -> RawSchema:
181+
"""Static method to decode the base64 encoded schema back to the dictionary
182+
183+
:param encoded_schema: holds a base64 representation of the schema
184+
:return: a raw schema instance
185+
"""
186+
decoded_raw_schema = base64.b64decode(encoded_schema.encode()).decode()
187+
return self.settings.json_loads(decoded_raw_schema)
188+
189189
def __setitem__(self, url: str, schema: RawSchema):
190190
logger.debug(f"Sqlite caching schema for url `{url}`")
191191
encoded_schema = self._encode_schema(schema)

src/qlient/settings.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
:author: Daniel Seifert
44
:created: 09.09.2021
55
"""
6+
import json
67

78

89
class Settings:
@@ -12,11 +13,15 @@ def __init__(
1213
self,
1314
introspect: bool = True,
1415
validate_variables: bool = True,
15-
validate_fields: bool = True
16+
validate_fields: bool = True,
17+
json_loads=json.loads,
18+
json_dumps=json.dumps,
1619
):
1720
self.introspect: bool = introspect
1821
self.validate_variables: bool = validate_variables
1922
self.validate_fields: bool = validate_fields
23+
self.json_loads = json_loads
24+
self.json_dumps = json_dumps
2025

2126
def __str__(self) -> str:
2227
"""Return a simple string representation of the settings"""

0 commit comments

Comments
 (0)