Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

67 lignes
1.8 KiB

  1. import json
  2. import pickle
  3. from enum import Enum
  4. from pathlib import Path
  5. from typing import Any, Callable, Union
  6. from .types import StrBytes
  7. class Protocol(str, Enum):
  8. json = 'json'
  9. pickle = 'pickle'
  10. def load_str_bytes(
  11. b: StrBytes,
  12. *,
  13. content_type: str = None,
  14. encoding: str = 'utf8',
  15. proto: Protocol = None,
  16. allow_pickle: bool = False,
  17. json_loads: Callable[[str], Any] = json.loads,
  18. ) -> Any:
  19. if proto is None and content_type:
  20. if content_type.endswith(('json', 'javascript')):
  21. pass
  22. elif allow_pickle and content_type.endswith('pickle'):
  23. proto = Protocol.pickle
  24. else:
  25. raise TypeError(f'Unknown content-type: {content_type}')
  26. proto = proto or Protocol.json
  27. if proto == Protocol.json:
  28. if isinstance(b, bytes):
  29. b = b.decode(encoding)
  30. return json_loads(b)
  31. elif proto == Protocol.pickle:
  32. if not allow_pickle:
  33. raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
  34. bb = b if isinstance(b, bytes) else b.encode()
  35. return pickle.loads(bb)
  36. else:
  37. raise TypeError(f'Unknown protocol: {proto}')
  38. def load_file(
  39. path: Union[str, Path],
  40. *,
  41. content_type: str = None,
  42. encoding: str = 'utf8',
  43. proto: Protocol = None,
  44. allow_pickle: bool = False,
  45. json_loads: Callable[[str], Any] = json.loads,
  46. ) -> Any:
  47. path = Path(path)
  48. b = path.read_bytes()
  49. if content_type is None:
  50. if path.suffix in ('.js', '.json'):
  51. proto = Protocol.json
  52. elif path.suffix == '.pkl':
  53. proto = Protocol.pickle
  54. return load_str_bytes(
  55. b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
  56. )