Skip to content

Commit d747bff

Browse files
committed
making new caching backwards compatible
1 parent 362e5d8 commit d747bff

File tree

2 files changed

+74
-45
lines changed

2 files changed

+74
-45
lines changed

astroquery/query.py

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import astropy.units as u
1919
from astropy.utils.console import ProgressBarOrSpinner
2020
import astropy.utils.data
21+
from astropy.utils import deprecated
22+
from astropy.utils.exceptions import AstropyDeprecationWarning
2123

2224
from astroquery import version, log, conf
2325
from astroquery.utils import system_tools
@@ -106,7 +108,7 @@ def hash(self):
106108
return self._hash
107109

108110
def request_file(self, cache_location):
109-
fn = os.path.join(cache_location, self.hash() + ".pickle")
111+
fn = cache_location.joinpath(self.hash() + ".pickle")
110112
return fn
111113

112114
def from_cache(self, cache_location, cache_timeout):
@@ -116,7 +118,7 @@ def from_cache(self, cache_location, cache_timeout):
116118
expired = False
117119
else:
118120
current_time = datetime.utcnow()
119-
cache_time = datetime.utcfromtimestamp(os.path.getmtime(request_file))
121+
cache_time = datetime.utcfromtimestamp(request_file.stat().st_mtime)
120122
expired = ((current_time-cache_time) > timedelta(seconds=cache_timeout))
121123
if not expired:
122124
with open(request_file, "rb") as f:
@@ -139,8 +141,8 @@ def remove_cache_file(self, cache_location):
139141
"""
140142
request_file = self.request_file(cache_location)
141143

142-
if os.path.exists(request_file):
143-
os.remove(request_file)
144+
if request_file.exists:
145+
request_file.unlink()
144146
else:
145147
raise FileNotFoundError(f"Tried to remove cache file {request_file} but "
146148
"it does not exist")
@@ -188,7 +190,7 @@ def __init__(self):
188190
olduseragent=S.headers['User-Agent']))
189191

190192
self.name = self.__class__.__name__.split("Class")[0]
191-
self.cache_location = None
193+
self._cache_location = None
192194

193195
def __call__(self, *args, **kwargs):
194196
""" init a fresh copy of self """
@@ -229,23 +231,23 @@ def _response_hook(self, response, *args, **kwargs):
229231
log.log(5, f"HTTP response\n{response_log}")
230232

231233
@property
232-
def _cache_location(self):
233-
cl = self.cache_location or os.path.join(paths.get_cache_dir(), 'astroquery', self.name)
234-
Path(cl).mkdir(parents=True, exist_ok=True)
234+
def cache_location(self):
235+
cl = self._cache_location or Path(paths.get_cache_dir(), 'astroquery', self.name)
236+
cl.mkdir(parents=True, exist_ok=True)
235237
return cl
236238

237-
def get_cache_location(self):
238-
return self._cache_location
239+
@cache_location.setter
240+
def cache_location(self, loc):
241+
self._cache_location = Path(loc)
239242

240243
def reset_cache_location(self):
241-
self.cache_location = None
244+
"""Resets the cache location to the default astropy cache"""
245+
self._cache_location = None
242246

243247
def clear_cache(self):
244248
"""Removes all cache files."""
245-
246-
cache_files = [x for x in os.listdir(self._cache_location) if x.endswith("pickle")]
247-
for fle in cache_files:
248-
os.remove(os.path.join(self._cache_location, fle))
249+
for fle in self.cache_location.glob("*.pickle"):
250+
fle.unlink()
249251

250252
def _request(self, method, url,
251253
params=None, data=None, headers=None,
@@ -317,10 +319,7 @@ def _request(self, method, url,
317319
json=json
318320
)
319321

320-
if (cache is not False) and conf.cache_active:
321-
cache = True
322-
else:
323-
cache = False
322+
cache &= conf.cache_active
324323

325324
if save:
326325
local_filename = url.split('/')[-1]
@@ -329,7 +328,7 @@ def _request(self, method, url,
329328
# ":" so replace them with an underscore
330329
local_filename = local_filename.replace(':', '_')
331330

332-
local_filepath = os.path.join(savedir or self._cache_location or '.', local_filename)
331+
local_filepath = os.path.join(savedir or self.cache_location or '.', local_filename)
333332

334333
response = self._download_file(url, local_filepath, cache=cache,
335334
continuation=continuation, method=method,
@@ -341,23 +340,23 @@ def _request(self, method, url,
341340
return local_filepath
342341
else:
343342
query = AstroQuery(method, url, **req_kwargs)
344-
if ((self._cache_location is None) or (not cache)):
343+
if (self.cache_location is None) or (not cache):
345344
with conf.set_temp("cache_active", False):
346345
response = query.request(self._session, stream=stream,
347346
auth=auth, verify=verify,
348347
allow_redirects=allow_redirects,
349348
json=json)
350349
else:
351-
response = query.from_cache(self._cache_location, conf.cache_timeout)
350+
response = query.from_cache(self.cache_location, conf.cache_timeout)
352351
if not response:
353352
response = query.request(self._session,
354-
self._cache_location,
353+
self.cache_location,
355354
stream=stream,
356355
auth=auth,
357356
allow_redirects=allow_redirects,
358357
verify=verify,
359358
json=json)
360-
to_cache(response, query.request_file(self._cache_location))
359+
to_cache(response, query.request_file(self.cache_location))
361360

362361
self._last_query = query
363362
return response
@@ -484,6 +483,8 @@ def _download_file(self, url, local_filepath, timeout=None, auth=None,
484483
return response
485484

486485

486+
@deprecated(since="v0.4.7", message=("The suspend_cache function is deprecated,"
487+
"Use the conf set_temp function instead."))
487488
class suspend_cache:
488489
"""
489490
A context manager that suspends caching.

astroquery/tests/test_cache.py

Lines changed: 49 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ def _login(self, username):
5151

5252

5353
def test_conf():
54+
conf.reset()
55+
5456
default_timeout = conf.cache_timeout
5557
default_active = conf.cache_active
5658

@@ -75,72 +77,75 @@ def test_conf():
7577

7678

7779
def test_basic_caching():
80+
conf.reset()
7881

7982
mytest = TestClass()
8083
assert conf.cache_active
8184

8285
mytest.clear_cache()
83-
assert len(os.listdir(mytest.get_cache_location())) == 0
86+
assert len(os.listdir(mytest.cache_location)) == 0
8487

8588
set_response(TEXT1)
8689

8790
resp = mytest.test_func(URL1)
8891
assert resp.content == TEXT1
89-
assert len(os.listdir(mytest.get_cache_location())) == 1
92+
assert len(os.listdir(mytest.cache_location)) == 1
9093

9194
set_response(TEXT2)
9295

9396
resp = mytest.test_func(URL2) # query that has not been cached
9497
assert resp.content == TEXT2
95-
assert len(os.listdir(mytest.get_cache_location())) == 2
98+
assert len(os.listdir(mytest.cache_location)) == 2
9699

97100
resp = mytest.test_func(URL1)
98101
assert resp.content == TEXT1 # query that was cached
99-
assert len(os.listdir(mytest.get_cache_location())) == 2 # no new cache file
102+
assert len(os.listdir(mytest.cache_location)) == 2 # no new cache file
100103

101104
mytest.clear_cache()
102-
assert len(os.listdir(mytest.get_cache_location())) == 0
105+
assert len(os.listdir(mytest.cache_location)) == 0
103106

104107
resp = mytest.test_func(URL1)
105108
assert resp.content == TEXT2 # Now get new response
106109

107110

108111
def test_change_location(tmpdir):
112+
conf.reset()
109113

110114
mytest = TestClass()
111-
default_cache_location = mytest.get_cache_location()
115+
default_cache_location = mytest.cache_location
112116

113-
assert paths.get_cache_dir() in default_cache_location
114-
assert "astroquery" in mytest.get_cache_location()
115-
assert mytest.name in mytest.get_cache_location()
117+
assert paths.get_cache_dir() in str(default_cache_location)
118+
assert "astroquery" in mytest.cache_location.parts
119+
assert mytest.name in mytest.cache_location.parts
116120

117-
new_loc = os.path.join(tmpdir, "new_dir")
121+
new_loc = "new_dir"
118122
mytest.cache_location = new_loc
119-
assert mytest.get_cache_location() == new_loc
123+
assert str(mytest.cache_location) == new_loc
120124

121125
mytest.reset_cache_location()
122-
assert mytest.get_cache_location() == default_cache_location
126+
assert mytest.cache_location == default_cache_location
123127

124128
Path(new_loc).mkdir(parents=True, exist_ok=True)
125129
with paths.set_temp_cache(new_loc):
126-
assert new_loc in mytest.get_cache_location()
127-
assert "astroquery" in mytest.get_cache_location()
128-
assert mytest.name in mytest.get_cache_location()
130+
assert new_loc in mytest.cache_location.parts
131+
assert "astroquery" in mytest.cache_location.parts
132+
assert mytest.name in mytest.cache_location.parts
129133

130134

131135
def test_login():
136+
conf.reset()
132137

133138
mytest = TestClass()
134139
assert conf.cache_active
135140

136141
mytest.clear_cache()
137-
assert len(os.listdir(mytest.get_cache_location())) == 0
142+
assert len(os.listdir(mytest.cache_location)) == 0
138143

139144
set_response(TEXT1) # Text 1 is set as the approved password
140145

141146
mytest.login("ceb")
142147
assert mytest.authenticated()
143-
assert len(os.listdir(mytest.get_cache_location())) == 0 # request should not be cached
148+
assert len(os.listdir(mytest.cache_location)) == 0 # request should not be cached
144149

145150
set_response(TEXT2) # Text 2 is not the approved password
146151

@@ -149,12 +154,13 @@ def test_login():
149154

150155

151156
def test_timeout():
157+
conf.reset()
152158

153159
mytest = TestClass()
154160
assert conf.cache_active
155161

156162
mytest.clear_cache()
157-
assert len(os.listdir(mytest.get_cache_location())) == 0
163+
assert len(os.listdir(mytest.cache_location)) == 0
158164

159165
conf.cache_timeout = 2 # Set to 2 sec so we can reach timeout easily
160166

@@ -174,21 +180,43 @@ def test_timeout():
174180

175181

176182
def test_deactivate():
183+
conf.reset()
177184

178185
mytest = TestClass()
179186
conf.cache_active = False
180187

181188
mytest.clear_cache()
182-
assert len(os.listdir(mytest.get_cache_location())) == 0
189+
assert len(os.listdir(mytest.cache_location)) == 0
183190

184191
set_response(TEXT1)
185192

186193
resp = mytest.test_func(URL1)
187194
assert resp.content == TEXT1
188-
assert len(os.listdir(mytest.get_cache_location())) == 0
195+
assert len(os.listdir(mytest.cache_location)) == 0
189196

190197
set_response(TEXT2)
191198

192199
resp = mytest.test_func(URL1)
193200
assert resp.content == TEXT2
194-
assert len(os.listdir(mytest.get_cache_location())) == 0
201+
assert len(os.listdir(mytest.cache_location)) == 0
202+
203+
conf.reset()
204+
assert conf.cache_active is True
205+
206+
with conf.set_temp('cache_active', False):
207+
mytest.clear_cache()
208+
assert len(os.listdir(mytest.cache_location)) == 0
209+
210+
set_response(TEXT1)
211+
212+
resp = mytest.test_func(URL1)
213+
assert resp.content == TEXT1
214+
assert len(os.listdir(mytest.cache_location)) == 0
215+
216+
set_response(TEXT2)
217+
218+
resp = mytest.test_func(URL1)
219+
assert resp.content == TEXT2
220+
assert len(os.listdir(mytest.cache_location)) == 0
221+
222+
assert conf.cache_active is True

0 commit comments

Comments
 (0)