Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# -*- coding: utf-8 -*- 

2 

3""" 

4certifi.py 

5~~~~~~~~~~ 

6 

7This module returns the installation location of cacert.pem or its contents. 

8""" 

9import os 

10 

11try: 

12 from importlib.resources import path as get_path, read_text 

13 

14 _CACERT_CTX = None 

15 _CACERT_PATH = None 

16 

17 def where(): 

18 # This is slightly terrible, but we want to delay extracting the file 

19 # in cases where we're inside of a zipimport situation until someone 

20 # actually calls where(), but we don't want to re-extract the file 

21 # on every call of where(), so we'll do it once then store it in a 

22 # global variable. 

23 global _CACERT_CTX 

24 global _CACERT_PATH 

25 if _CACERT_PATH is None: 

26 # This is slightly janky, the importlib.resources API wants you to 

27 # manage the cleanup of this file, so it doesn't actually return a 

28 # path, it returns a context manager that will give you the path 

29 # when you enter it and will do any cleanup when you leave it. In 

30 # the common case of not needing a temporary file, it will just 

31 # return the file system location and the __exit__() is a no-op. 

32 # 

33 # We also have to hold onto the actual context manager, because 

34 # it will do the cleanup whenever it gets garbage collected, so 

35 # we will also store that at the global level as well. 

36 _CACERT_CTX = get_path("certifi", "cacert.pem") 

37 _CACERT_PATH = str(_CACERT_CTX.__enter__()) 

38 

39 return _CACERT_PATH 

40 

41 

42except ImportError: 

43 # This fallback will work for Python versions prior to 3.7 that lack the 

44 # importlib.resources module but relies on the existing `where` function 

45 # so won't address issues with environments like PyOxidizer that don't set 

46 # __file__ on modules. 

47 def read_text(_module, _path, encoding="ascii"): 

48 with open(where(), "r", encoding=encoding) as data: 

49 return data.read() 

50 

51 # If we don't have importlib.resources, then we will just do the old logic 

52 # of assuming we're on the filesystem and munge the path directly. 

53 def where(): 

54 f = os.path.dirname(__file__) 

55 

56 return os.path.join(f, "cacert.pem") 

57 

58 

59def contents(): 

60 return read_text("certifi", "cacert.pem", encoding="ascii")