-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathfatsecret.py
225 lines (199 loc) · 10.2 KB
/
fatsecret.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import hashlib#for computing hash
from rauth.service import OAuth1Service #see https://github.com/litl/rauth for more info
import shelve #for persistent caching of tokens, hashes,etc.
import time
import datetime
#get your consumer key and secret after registering as a developer here: https://oauth.withings.com/en/partner/add
#FIXME add method to set default units and make it an optional argument to the constructor
class Fatsecret:
def __init__(self,consumer_key,consumer_secret,verbose=0,cache_name='tokens.dat'):
#cache stores tokens and hashes on disk so we avoid
#requesting them every time.
self.cache=shelve.open(cache_name,writeback=False)
self.verbose=verbose
self.oauth=OAuth1Service(
name='fatsecret',
consumer_key=consumer_key,
consumer_secret=consumer_secret,
request_token_url='http://www.fatsecret.com/oauth/request_token',
access_token_url='http://www.fatsecret.com/oauth/access_token',
authorize_url='http://www.fatsecret.com/oauth/authorize',
header_auth=False)
self.access_token = self.cache.get('fatsecret_access_token',None)
self.access_token_secret = self.cache.get('fatsecret_access_token_secret',None)
self.request_token = self.cache.get('fatsecret_request_token',None)
self.request_token_secret = self.cache.get('fatsecret_request_token_secret',None)
self.pin= self.cache.get('fatsecret_pin',None)
#If this is our first time running- get new tokens
if (self.need_request_token()):
self.get_request_token()
got_access_token=self.get_access_token()
if( not got_access_token):
print "Error: Unable to get access token"
def dbg_print(self,txt):
if self.verbose==1:
print txt
def get_request_token(self):
self.request_token,self.request_token_secret = self.oauth.get_request_token(method='GET',params={'oauth_callback':'oob'})
authorize_url=self.oauth.get_authorize_url(self.request_token)
#the pin you want here is the string that appears after oauth_verifier on the page served
#by the authorize_url
print 'Visit this URL in your browser then login: ' + authorize_url
self.pin = raw_input('Enter PIN from browser: ')
self.cache['fatsecret_request_token']=self.request_token
self.cache['fatsecret_request_token_secret']=self.request_token_secret
self.cache['fatsecret_pin']=self.pin
print "fatsecret_pin is ",self.cache.get('fatsecret_pin')
def need_request_token(self):
#created this method because i'm not clear when request tokens need to be obtained, or how often
if (self.request_token==None) or (self.request_token_secret==None) or (self.pin==None):
return True
else:
return False
def get_access_token(self):
print "in get_access_token"
response=self.oauth.get_access_token('GET',
request_token=self.request_token,
request_token_secret=self.request_token_secret,
params={'oauth_verifier':self.pin})
data=response.content
print response.content
self.access_token=data.get('oauth_token',None)
self.access_token_secret=data.get('oauth_token_secret',None)
self.cache['fatsecret_access_token']=self.access_token
self.cache['fatsecret_access_token_secret']=self.access_token_secret
if not(self.access_token) or not(self.access_token_secret):
print "access token expired "
return False
else:
return True
def food_get(self,food_id):
"""Returns nutrition information and the corresponding fatsecret information URL for the specified food_id
food_ids may be obtained by using foods_search()"""
if food_id is None:
return None
params={'method': 'food.get','food_id':food_id,'format':'json'}
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
return response.content
def foods_get_favorites(self):
params={'method': 'foods.get_favorites','oauth_token': self.access_token,'format':'json'}
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
if response.content.get('foods'):
return response.content['foods']['food']
def foods_get_most_eaten(self,meal=None):
params={'method': 'foods.get_most_eaten','oauth_token': self.access_token,'format':'json'}
if meal in ['breakfast','lunch','dinner','other']:
params['meal']=meal
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
if response.content.get('foods'):
return response.content['foods']['food']
def foods_get_recently_eaten(self,meal=None):
params={'method': 'foods.get_recently_eaten','oauth_token': self.access_token,'format':'json'}
if meal in ['breakfast','lunch','dinner','other']:
params['meal']=meal
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
if response.content.get('foods'):
return response.content['foods']['food']
def foods_search(self,search_expression,page_number=None,max_results=None):
params={'method': 'foods.search','oauth_token': self.access_token,'search_expression':search_expression,'format':'json'}
if page_number!=None:
params['page_number'] = page_number
if max_results!=None:
params['max_results'] = max_results
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
return response.content
def food_entries_get_month(self,date=datetime.datetime.now()):
params={'method': 'food_entries.get_month','format':'json'}
params['date']=int(round(time.mktime(date.timetuple())/60/60/24))
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
print response.content
if response.content['month'].get('day'):
tmp=response.content['month']['day']
else:
#months without data will still contain a 'month' key, but not a 'day' key
tmp=None
#result=[(i['carbohydrate'],i['fat'],i['protein'],i['calories'],i['date_int']) for i in tmp]
return tmp
def saved_meals_get(self):
"""Returns a list where each item is formatted like
{"saved_meal": {"meals": "Lunch,Other", "saved_meal_description": "A high impact energy meal - terrific for the great outdoors!", "saved_meal_id": "1111111", "saved_meal_name": "Power Snack" }"""
params={'method': 'saved_meals.get','format':'json'}
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
if response.content.get('saved_meals'):
tmp=response.content['saved_meals']['saved_meal']
else:
tmp=None
return tmp
def weights_get_month(self,date=datetime.datetime.now()):
"""Return date_int and weight in kg for each day in requested month"""
params={'method': 'weights.get_month','format':'json'}
params['date']=int(round(time.mktime(date.timetuple())/60/60/24))
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
print response.content
#note that every valid data point has weight_kg and date_int fields but
#may also optionally have a weight_comment field
#also note that you in response.content you also get from_date_int and to_date_int keys
#that specify the range of dates included in the requested month
if response.content['month'].get('day'):
tmp=response.content['month']['day']
else:
tmp=None
return tmp
def exercise_entries_get_month(self,date=datetime.datetime.now()):
"""Return date_int and calories burned for each day in requested month"""
params={'method': 'exercise_entries.get_month','format':'json'}
params['date']=int(round(time.mktime(date.timetuple())/60/60/24))
response=self.oauth.get(
'http://platform.fatsecret.com/rest/server.api',
params=params,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
header_auth=False)
print response.content
#note that every valid data point has weight_kg and date_int fields but
#may also optionally have a weight_comment field
if response.content['month'].get('day'):
tmp=response.content['month']['day']
else:
tmp=None
return tmp