File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change 13
13
14
14
from __future__ import annotations
15
15
16
+ import json
16
17
import typing as ty
17
18
import warnings
18
19
from io import BytesIO
@@ -368,16 +369,38 @@ def get_code(self):
368
369
"""Return the canonical extension type code."""
369
370
return self .code
370
371
372
+ # Canonical access to extension content
373
+ # Follows the lead of httpx.Response .content, .text and .json()
374
+ # properties/methods
371
375
@property
372
376
def content (self ) -> bytes :
373
377
"""Return the extension content as raw bytes."""
374
378
self ._sync ()
375
379
return self ._content
376
380
381
+ @property
382
+ def text (self ) -> str :
383
+ """Attempt to decode the extension content as text.
384
+
385
+ The encoding is determined by the `encoding` attribute, which may be
386
+ set by the user or subclass. If not set, the default encoding is 'utf-8'.
387
+ """
388
+ return self .content .decode (self .encoding or 'utf-8' )
389
+
390
+ def json (self ) -> ty .Any :
391
+ """Attempt to decode the extension content as JSON.
392
+
393
+ If the content is not valid JSON, a JSONDecodeError or UnicodeDecodeError
394
+ will be raised.
395
+ """
396
+ return json .loads (self .content )
397
+
377
398
def get_content (self ) -> T :
378
399
"""Return the extension content in its runtime representation.
379
400
380
401
This method may return a different type for each extension type.
402
+ For simple use cases, consider using ``.content``, ``.text`` or ``.json()``
403
+ instead.
381
404
"""
382
405
if self ._object is None :
383
406
self ._object = self ._unmangle (self ._content )
You can’t perform that action at this time.
0 commit comments