Coverage for pyguymer3/download_file.py: 4%

24 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-08 18:47 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def download_file( 

5 sess, 

6 url, 

7 fname, 

8 /, 

9 *, 

10 cookies = None, 

11 debug = __debug__, 

12 headers = None, 

13 setModificationTime = True, 

14 timeout = 10.0, 

15 verify = True, 

16): 

17 """GET a URL and save the content in a file 

18 

19 This function performs a HTTP GET operation on a URL and saves the content 

20 in a file, and optionally sets the Last-Modified time if available. 

21 

22 Parameters 

23 ---------- 

24 sess : requests.sessions.Session 

25 the :mod:`requests` session to use 

26 url : str 

27 the URL 

28 fname : str 

29 the name of the file to save the content in 

30 cookies : dict, optional 

31 the cookie jar 

32 debug : bool, optional 

33 print debug messages 

34 headers : dict, optional 

35 extra headers to send 

36 timeout : float, optional 

37 the timeout of the GET request 

38 setModificationTime : bool, optional 

39 set the Last-Modified time if available. 

40 verify : bool, optional 

41 verify the server's certificates 

42 

43 Returns 

44 ------- 

45 resp : bool 

46 the success of the download 

47 

48 Notes 

49 ----- 

50 Copyright 2017 Thomas Guymer [1]_ 

51 

52 References 

53 ---------- 

54 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3 

55 """ 

56 

57 # Import standard modules ... 

58 import email 

59 import email.utils 

60 import os 

61 

62 # Import sub-functions ... 

63 from .download import download 

64 

65 # Populate default values ... 

66 if cookies is None: 

67 cookies = {} 

68 if headers is None: 

69 headers = {} 

70 

71 # ************************************************************************** 

72 

73 # Try to download the file ... 

74 resp = download( 

75 sess, 

76 "get", 

77 url, 

78 cookies = cookies, 

79 headers = headers, 

80 timeout = timeout, 

81 verify = verify, 

82 ) 

83 

84 # Check response ... 

85 if resp is False: 

86 return False 

87 

88 # Save file to disk ... 

89 dname = os.path.dirname(fname) 

90 if len(dname) > 0: 

91 if not os.path.exists(dname): 

92 os.makedirs(dname) 

93 with open(fname, "wb") as fObj: 

94 fObj.write(resp.content) 

95 

96 # Change modification time if present ... 

97 if setModificationTime and "Last-Modified" in resp.headers: 

98 if debug: 

99 print(f"DEBUG: Setting the modification time of \"{fname}\" to that of \"{url}\".") 

100 modtime = email.utils.mktime_tz(email.utils.parsedate_tz(resp.headers["Last-Modified"])) 

101 os.utime(fname, (modtime, modtime)) 

102 

103 # Return answer ... 

104 return True