-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnestor_api.py
198 lines (156 loc) · 6.66 KB
/
nestor_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# -*- coding: utf-8 -*-
#!/usr/bin/python
from datetime import datetime
import os
import logging
import requests
import json
import time
from pprint import pprint
# Instantiate logger instance
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
MENUS_DIRECTORY = './menus/nestor'
RAW_MENUS_DIRECTORY = MENUS_DIRECTORY + '/raw/'
CUSTOM_MENUS_DIRECTORY = MENUS_DIRECTORY + '/custom/'
EMPTY_MENU_FILE = './menus/empty_menu.json'
NESTOR_REQUEST_URL = "https://api-nestor.com/menu/75001"
# TODO : The kitchen id (number before menu iun url) seems to change the
# availabilities of some items : understand why
NESTOR_BASE_URL = "https://www.nestorparis.com/"
NESTOR_LOGO = "https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAAd9AAAAJDg4ZDQ2ZTg4LTM4OGMtNDZiYi1iNTRhLWNkNzcyNTc5YjkzNA.png"
##########################################################################
############################## FILE MANAGEMENT #################
##########################################################################
def create_directories_if_needed():
if not os.path.exists(os.path.dirname(RAW_MENUS_DIRECTORY)):
logger.info('Creating ' + RAW_MENUS_DIRECTORY + '...')
try:
os.makedirs(os.path.dirname(RAW_MENUS_DIRECTORY))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
if not os.path.exists(os.path.dirname(CUSTOM_MENUS_DIRECTORY)):
logger.info('Creating ' + CUSTOM_MENUS_DIRECTORY + '...')
try:
os.makedirs(os.path.dirname(CUSTOM_MENUS_DIRECTORY))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
def get_todays_raw_file_name():
return 'nestor-raw-' + time.strftime("%d-%m-%Y") + '.json'
def get_todays_custom_file_name():
return 'nestor-custom-' + time.strftime("%d-%m-%Y") + '.json'
def save_todays_menu_raw_format(menu):
file_name = get_todays_raw_file_name()
logger.info("Saving raw file " + file_name + " ...")
with open(RAW_MENUS_DIRECTORY + file_name, 'w') as file:
file.write(menu.text.encode('utf-8'))
def save_todays_menu_custom_format(menu):
file_name = get_todays_custom_file_name()
logger.info("Saving custom file " + file_name + " ...")
# Do reformat here
custom_menu = format_raw_menu(menu)
with open(CUSTOM_MENUS_DIRECTORY + file_name, 'w') as file:
file.write(json.dumps(custom_menu))
def is_today(sample_date):
sample_date = datetime.strptime(sample_date[0:10], "%Y-%m-%d").date()
return datetime.today().day == sample_date.day and datetime.today().year == sample_date.year and datetime.today().month == sample_date.month
def format_raw_menu(raw_menu):
custom_menu = {'menu': {},
'meal_categories': []}
try:
todays_menu = next(x['menus'][0] for x in raw_menu['menus']
if is_today(x['date']))
except StopIteration:
with open(EMPTY_MENU_FILE) as f:
return json.load(f)
meal_category = 'only_category'
meal_category_label = "Menu du jour !"
entree = {
'category_tag': meal_category,
'category_label': meal_category_label,
'title': todays_menu['entree']['name'],
'price': todays_menu['price']/100,
'productType': 'entree',
'productId': '',
'shortDescription': "Entrée",
'description': todays_menu['entree']['ingredients'],
'image': {
'url': todays_menu['entree']['image_url'],
'id': ''
}
}
dish = {
'category_tag': meal_category,
'category_label': meal_category_label,
'title': todays_menu['dish']['name'],
'price': todays_menu['price']/100,
'productType': 'dish',
'productId': '',
'shortDescription': "Plat principal",
'description': todays_menu['dish']['ingredients'],
'image': {
'url': todays_menu['dish']['image_url'],
'id': ''
}
}
dessert = {
'category_tag': meal_category,
'category_label': meal_category_label,
'title': todays_menu['dessert']['name'],
'price': todays_menu['price']/100,
'productType': 'dessert',
'productId': '',
'shortDescription': "Dessert",
'description': todays_menu['dessert']['ingredients'],
'image': {
'url': todays_menu['dessert']['image_url'],
'id': ''
}
}
meal_category_item = {'tag': meal_category,
'label': meal_category_label}
custom_menu['meal_categories'].append(meal_category_item)
custom_menu['menu'][meal_category] = [entree, dish, dessert]
return custom_menu
##########################################################################
############################## TODAYS MENU #################
##########################################################################
def fetch_todays_nestor_menu():
# Request Nestor website to get daily data
logger.info("Fetching today's data...")
try:
r = requests.get(NESTOR_REQUEST_URL)
except:
r = None
return r
def fetch_and_save_todays_menu_if_needed():
create_directories_if_needed()
if not os.path.exists(RAW_MENUS_DIRECTORY + get_todays_raw_file_name()) or not os.path.exists(CUSTOM_MENUS_DIRECTORY + get_todays_custom_file_name()):
menu = fetch_todays_nestor_menu()
save_todays_menu_raw_format(menu)
with open(RAW_MENUS_DIRECTORY + get_todays_raw_file_name()) as data_file:
json_menu = json.load(data_file)
save_todays_menu_custom_format(json_menu)
def get_todays_data():
with open(CUSTOM_MENUS_DIRECTORY + get_todays_custom_file_name()) as data_file:
data = json.load(data_file)
return data
##########################################################################
################### USEFUL PRIVATE METHODS #################
def get_product_url(product_id):
return NESTOR_BASE_URL
def get_propositions(selected_category):
menu = get_todays_data()['menu']
return [prop for prop in menu[selected_category]] if selected_category in menu else None
def get_todays_categories():
data = get_todays_data()
available_categories = [x for x in data['meal_categories']]
return available_categories
##########################################################################
######################### PUBLIC METHODS ######################
def ask_nestor(query, param1=None):
logger.info("Asking nestor for:\n - query=%s\n - param1=%s", query, param1)
fetch_and_save_todays_menu_if_needed()
return get_propositions(param1)