PNA.fi koodi

pnalib.py 883B

123456789101112131415161718192021222324252627282930
  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):
  6. return get_file(url, temp_fname, use_old, jsonp_load)
  7. def get_json_file(url, temp_fname, use_old):
  8. return get_file(url, temp_fname, use_old, json.load)
  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):
  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. try:
  21. with open(temp_fname, "r", encoding="utf-8") as fin:
  22. return consumer(fin)
  23. except OSError as e:
  24. pass