Coverage for /pythoncovmergedfiles/medio/medio/src/pydantic/pydantic/deprecated/parse.py: 36%

42 statements  

« prev     ^ index     » next       coverage.py v7.2.3, created at 2023-04-27 07:38 +0000

1from __future__ import annotations 

2 

3import json 

4import pickle 

5import warnings 

6from enum import Enum 

7from pathlib import Path 

8from typing import Any, Callable 

9 

10from typing_extensions import deprecated 

11 

12 

13class Protocol(str, Enum): 

14 json = 'json' 

15 pickle = 'pickle' 

16 

17 

18@deprecated('load_str_bytes is deprecated.') 

19def load_str_bytes( 

20 b: str | bytes, 

21 *, 

22 content_type: str | None = None, 

23 encoding: str = 'utf8', 

24 proto: Protocol | None = None, 

25 allow_pickle: bool = False, 

26 json_loads: Callable[[str], Any] = json.loads, 

27) -> Any: 

28 warnings.warn('load_str_bytes is deprecated.', DeprecationWarning, stacklevel=2) 

29 if proto is None and content_type: 

30 if content_type.endswith(('json', 'javascript')): 

31 pass 

32 elif allow_pickle and content_type.endswith('pickle'): 

33 proto = Protocol.pickle 

34 else: 

35 raise TypeError(f'Unknown content-type: {content_type}') 

36 

37 proto = proto or Protocol.json 

38 

39 if proto == Protocol.json: 

40 if isinstance(b, bytes): 

41 b = b.decode(encoding) 

42 return json_loads(b) 

43 elif proto == Protocol.pickle: 

44 if not allow_pickle: 

45 raise RuntimeError('Trying to decode with pickle with allow_pickle=False') 

46 bb = b if isinstance(b, bytes) else b.encode() 

47 return pickle.loads(bb) 

48 else: 

49 raise TypeError(f'Unknown protocol: {proto}') 

50 

51 

52@deprecated('load_file is deprecated.') 

53def load_file( 

54 path: str | Path, 

55 *, 

56 content_type: str | None = None, 

57 encoding: str = 'utf8', 

58 proto: Protocol | None = None, 

59 allow_pickle: bool = False, 

60 json_loads: Callable[[str], Any] = json.loads, 

61) -> Any: 

62 warnings.warn('load_file is deprecated.', DeprecationWarning, stacklevel=2) 

63 path = Path(path) 

64 b = path.read_bytes() 

65 if content_type is None: 

66 if path.suffix in ('.js', '.json'): 

67 proto = Protocol.json 

68 elif path.suffix == '.pkl': 

69 proto = Protocol.pickle 

70 

71 return load_str_bytes( 

72 b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads 

73 )