PNA.fi koodi

pnalib.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. try:
  7. return get_file(url, temp_fname, use_old, jsonp_load, allow_old)
  8. except json.decoder.JSONDecodeError as e:
  9. print("Failed to parse JSON from {}".format(temp_fname))
  10. raise
  11. def get_json_file(url, temp_fname, use_old, allow_old=True):
  12. try:
  13. return get_file(url, temp_fname, use_old, json.load, allow_old)
  14. except json.decoder.JSONDecodeError as e:
  15. print("Failed to parse JSON from {}".format(temp_fname))
  16. raise
  17. def jsonp_load(fp):
  18. return json.loads(fp.read()[1:-2])
  19. def read_all(fp):
  20. return fp.read()
  21. def get_file(url, temp_fname, use_old, consumer=read_all, allow_old=True):
  22. if not use_old or not os.path.isfile(temp_fname):
  23. try:
  24. urllib.request.urlretrieve(url, temp_fname)
  25. except urllib.error.HTTPError as e:
  26. print("Failed to download {url}".format(url=url))
  27. # Juvenes may fail with error code 500 if food is not available
  28. if not allow_old:
  29. return None
  30. try:
  31. with open(temp_fname, "r", encoding="utf-8") as fin:
  32. return consumer(fin)
  33. except OSError as e:
  34. pass