MCPcopy Create free account
hub / github.com/Apress/python-for-matlab-development / fix_img_tiles

Function fix_img_tiles

code/bin/patch_cartopy.py:101–153  ·  view source on GitHub ↗

Modify cartopy/io/img_tiles.py to use requests.get() instead of urllib.request.Request() to download an image tile.

()

Source from the content-addressed store, hash-verified

99 print(f'Wrote updated {str(P)}')
100# }}}
101def fix_img_tiles(): # {{{
102 """
103 Modify cartopy/io/img_tiles.py to use
104 requests.get()
105 instead of
106 urllib.request.Request()
107 to download an image tile.
108 """
109 cartopy_io_dir = cartopy.io.__path__
110
111 if not cartopy_io_dir:
112 print(f"Unable to determine cartopy.io's location, exit")
113 return
114
115 P = pathlib.Path(cartopy_io_dir[0]) / 'img_tiles.py'
116 if not P.exists():
117 print(f"{str(P)} doesn't exist, exit")
118 return
119
120 lines_in = P.read_text().split('\n')
121 if 'import requests' in lines_in:
122 print(f'{str(P)} already uses requests module, nothing done')
123 return
124
125 shutil.copy(str(P), f'{str(P)}.bak') # backup the original version
126 print(f'Wrote backup {str(P)}.bak')
127
128 New = [
129 'request = requests.get(url, stream=True)',
130 'request.raw.decode_content = True',
131 'img = Image.open(request.raw)',
132 ]
133
134 lines_out = []
135 request_start = 0
136 for L in lines_in:
137 if re.search(r'^import\s+cartopy\s*$', L):
138 lines_out.append('import requests')
139 lines_out.append(L)
140 elif re.search(r'^\s+request\s+=\s*', L):
141 request_start = 1
142 lines_out.append(f'#{L}')
143 spaces = ' ' * L.find('r') # 12
144 lines_out.append(f'{spaces}{New[0]}')
145 lines_out.append(f'{spaces}{New[1]}')
146 lines_out.append(f'{spaces}{New[2]}')
147 elif 0 < request_start < 5:
148 request_start += 1
149 lines_out.append(f'#{L}')
150 else:
151 lines_out.append(L)
152 P.write_text('\n'.join(lines_out))
153 print(f'Wrote updated {str(P)}')
154# }}}
155def main():
156 fix_geos()

Callers 1

mainFunction · 0.85

Calls 1

copyMethod · 0.80

Tested by

no test coverage detected