PNA.fi koodi

pnalib.py 1011B

1234567891011121314151617181920212223242526272829303132
  1. import os.path
  2. import urllib.request
  3. import urllib.error
  4. import json
  5. def get_jsonp_file(url, temp_fname, use_old, allow_old=True):
  6. return get_file(url, temp_fname, use_old, jsonp_load, allow_old)
  7. def get_json_file(url, temp_fname, use_old, allow_old=True):
  8. return get_file(url, temp_fname, use_old, json.load, allow_old)
  9. def jsonp_load(fp):
  10. return json.loads(fp.read()[1:-2])
  11. def read_all(fp):
  12. return fp.read()
  13. def get_file(url, temp_fname, use_old, consumer=read_all, allow_old=True):
  14. if not use_old or not os.path.isfile(temp_fname):
  15. try:
  16. urllib.request.urlretrieve(url, temp_fname)
  17. except urllib.error.HTTPError as e:
  18. print("Failed to download {url}".format(url=url))
  19. # Juvenes may fail with error code 500 if food is not available
  20. if not allow_old:
  21. return None
  22. try:
  23. with open(temp_fname, "r", encoding="utf-8") as fin:
  24. return consumer(fin)
  25. except OSError as e:
  26. pass