PNA.fi koodi

amica.py 3.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import datetime
  2. import os
  3. import urllib.request
  4. import urllib.error
  5. import json
  6. restaurant_info = [
  7. [ "(TaY) Amica Minerva", "http://www.amica.fi/minerva", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=7381" ],
  8. [ "(TaY) Tampereen normaalikoulun ravintola", "http://www.amica.fi/tampereennormaalikoulu", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=6655" ],
  9. [ "(TTY) Ravintola Reaktori", "http://www.amica.fi/reaktori", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=69171" ]
  10. ]
  11. def get_restaurants(use_old, week):
  12. today = datetime.date.today()
  13. week_day = today.isocalendar()[2]
  14. this_monday = today - datetime.timedelta(days=week_day-1)
  15. week_date = this_monday.strftime("%Y-%m-%d")
  16. restaurants = []
  17. for count, info in enumerate(restaurant_info):
  18. title = info[0]
  19. url = info[4]
  20. temp_fname = "amica_{count}.temp.js".format(count = count)
  21. url = "{url}&weekDate={week_date}".format(url=url, week_date=week_date)
  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. try:
  28. with open(temp_fname, "r", encoding="utf-8") as fin:
  29. data = json.load(fin)
  30. except OSError as e:
  31. continue
  32. week_foods = {}
  33. lunch_menus = data["LunchMenus"]
  34. for week_day, lunch_menu in enumerate(lunch_menus):
  35. current_day_foods = []
  36. set_menus = lunch_menu["SetMenus"]
  37. html = lunch_menu["Html"]
  38. if len(html):
  39. menus = html.split("<p>")
  40. for set_menu in menus:
  41. meals = set_menu.split("<br />")
  42. food = []
  43. for meal in meals:
  44. parts = meal.split("(")
  45. current_food = parts[0]
  46. diets = [s.strip() for s in parts.split(")")[0].split(",")]
  47. if diets:
  48. current_food += " ({allergies})".format(allergies=", ".join(diets))
  49. food.append(current_food)
  50. current_day_foods.append("\n".join(food))
  51. else:
  52. for set_menu in set_menus:
  53. meals = set_menu["Meals"]
  54. food = []
  55. for meal in meals:
  56. current_food = meal["Name"]
  57. if "Diets" in meal:
  58. current_food += " ({allergies})".format(allergies=", ".join(meal["Diets"]))
  59. food.append(current_food)
  60. current_day_foods.append("\n".join(food))
  61. week_foods[week_day] = current_day_foods
  62. restaurants.append([title, "", week, week_foods, info])
  63. return restaurants