def authPart1(self): f = FlickrAPI(api_key=self.api_key, api_secret=self.api_secret, callback_url= web.ctx.homedomain + '/auth/flickrAuth?') auth_props = f.get_authentication_tokens(perms='write') auth_url = auth_props['auth_url'] #Store this token in a session or something for later use in the next step. self.oauth_token = auth_props['oauth_token'] self.oauth_token_secret = auth_props['oauth_token_secret'] return auth_url
def __init__(self, api_key='', api_secret=''): self.base = 'https://farm{farmid}.staticflickr.com/{serverid}/{id}_{secret}_o.{minetype}' try: with open('flickr.token', 'r') as f: token = pickle.load(f) self.flickr = FlickrAPI( api_key, api_secret, oauth_token=token['oauth_token'], oauth_token_secret=token['oauth_token_secret']) except: print 'first run!' f = FlickrAPI(api_key=api_key, api_secret=api_secret, callback_url='oob') auth_props = f.get_authentication_tokens(perms=u'write') auth_url = auth_props['auth_url'] oauth_token = auth_props['oauth_token'] oauth_token_secret = auth_props['oauth_token_secret'] print('open the url in browser and input the code:\n' + auth_url) oauth_verifier = self.toUnicodeOrBust(raw_input('verifier code:')) f2 = FlickrAPI(api_key=api_key, api_secret=api_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) authorized_tokens = f2.get_auth_tokens(oauth_verifier) final_oauth_token = authorized_tokens['oauth_token'] final_oauth_token_secret = authorized_tokens['oauth_token_secret'] token = { 'oauth_token': final_oauth_token, 'oauth_token_secret': final_oauth_token_secret } with open('flickr.token', 'w') as f: pickle.dump(token, f) self.flickr = FlickrAPI( api_key=api_key, api_secret=api_secret, oauth_token=final_oauth_token, oauth_token_secret=final_oauth_token_secret)
import cPickle as pickle from flickr import FlickrAPI from pprint import pprint # my_api_key='33a85d0de9040f3d12ed5d17bad02210' # my_api_secret='0a255e264884b059' my_api_key = 'af997fbb975e9e112d3d96b64f6d3ab5' my_api_secret = '384e545fe39b978e' # Part 1 - get online authorisation first_api_handle = FlickrAPI(api_key=my_api_key, api_secret=my_api_secret, callback_url='http://bowsy.me.uk/test/test.php') auth_props = first_api_handle.get_authentication_tokens(perms='delete') auth_url = auth_props['auth_url'] oauth_token = auth_props['oauth_token'] oauth_token_secret = auth_props['oauth_token_secret'] print 'Connect with Flickr via: %s' % auth_url # Get final tokens oauth_token_returned=raw_input('oauth_token_returned=') oauth_verifier_returned=raw_input('oauth_verifier_returned=') second_api_handle = FlickrAPI(api_key=my_api_key, api_secret=my_api_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret )
def get(self): url = '' ps = '' albums = {} y_albums = {} auth = False F_TOKEN = Settings.get('F_TOKEN') F_TOKEN_SECRET = Settings.get('F_TOKEN_SECRET') if F_TOKEN and F_TOKEN_SECRET: f = FlickrAPI(api_key = F_API_KEY, api_secret= F_API_SECRET, oauth_token= F_TOKEN, oauth_token_secret= F_TOKEN_SECRET) try: result = f.get('flickr.test.null') if result['stat'] == 'ok': auth = True except: auth = False if not auth: f = FlickrAPI(api_key=F_API_KEY, api_secret=F_API_SECRET, callback_url='http://fytunnel.appspot.com/callback/') #callback_url='http://localhost:10080/callback/') auth_props = f.get_authentication_tokens(perms = 'read') auth_url = auth_props['auth_url'] #Store this token in a session or something for later use in the next step. self.session['oauth_token'] = auth_props['oauth_token'] self.session['oauth_token_secret'] = auth_props['oauth_token_secret'] self.redirect(auth_url) else: f = FlickrAPI(api_key = F_API_KEY, api_secret= F_API_SECRET, oauth_token= F_TOKEN, oauth_token_secret= F_TOKEN_SECRET) user = f.get('flickr.test.login') data = f.get('flickr.photosets.getList', params={'user_id': user['user']['id']}) albums = {} if data['stat'] == 'ok': for item in data['photosets']['photoset']: id = item['id'] albums[id] = {} albums[id]['id'] = id albums[id]['photos'] = item['photos'] albums[id]['title'] = item['title']['_content'] albums[id]['description'] = item['description']['_content'] ''' a = flickr_api.auth.AuthHandler.fromdict(flickr_auth) flickr_api.set_auth_handler(a) u = flickr_api.test.login() ps = u.getPhotosets() ''' for id, item in albums.iteritems(): a = Album.get_by_id(id) if a is None: a = Album(title = item['title'],description = item['description'], flikr_id = item['id'], yaf_id = '', id = id) a.put() if a.yaf_id == '': url = 'http://api-fotki.yandex.ru/api/users/protasov-s/albums/?format=json' data = json.dumps({'title':item['title'], 'summary':item['description'], 'password':item['id']}) req = urllib2.Request(url, data, {'Accept': 'application/json','Content-Type': 'application/json; charset=utf-8; type=entry;', 'Authorization':'OAuth ' + yaf_token}) f = urllib2.urlopen(req) data = json.load(f) a.yaf_id = data['id'] a.put() f.close() if a.title != item['title'] or a.description != item['description']: a.title = item['title'] a.description = item['description'] url = 'http://api-fotki.yandex.ru/api/users/protasov-s/album/%s/?format=json' % a.yaf_id.split(':')[-1] result = urlfetch.fetch(url=url,headers={'Accept': 'application/json', 'Authorization':'OAuth ' + yaf_token}) if result.status_code == 200: yalbum = json.loads(result.content) yalbum['title'] = item['title'] yalbum['summary'] = item['description'] yalbum_data = json.dumps(yalbum) result = urlfetch.fetch(url=url, payload=yalbum_data, method=urlfetch.PUT, headers={'Accept': 'application/json','Content-Type': 'application/json; charset=utf-8; type=entry;', 'Authorization':'OAuth ' + yaf_token}) item['yaf_id'] = a.yaf_id url = 'http://api-fotki.yandex.ru/api/users/protasov-s/albums/published/' result = urlfetch.fetch(url=url, headers={'Accept': 'application/json', 'Authorization':'OAuth ' + yaf_token}) data = json.loads(result.content) for a in data['entries']: y_albums[a['id']] = a template_values = { 'auth':auth, 'menu':MENU, 'active':'index', 'albums':albums, 'url':url, 'y_albums':y_albums } template = JINJA_ENVIRONMENT.get_template('index.tpl') html = template.render(template_values) self.response.write(html)
from flickr import FlickrAPI auth_file = 'AUTH.key' auth = dict([map(lambda x: x.strip(), l.split('=')) \ for l in open(auth_file).readlines()]) if not 'KEY' in auth: print 'please create an api key in the flickr app-garden and add to AUTH.key' raise if not 'TOKEN' in auth: f = FlickrAPI(api_key=auth['KEY'], api_secret=auth['SECRET'], callback_url='http://www.example.com/callback/') visit = f.get_authentication_tokens()['auth_url'] print 'please visit %s and add TOKEN and VERIFIER to AUTH.key'%visit raise f = FlickrAPI(api_key=auth['KEY'], api_secret=auth['SECRET'], oauth_token=auth['TOKEN'], oauth_token_secret=auth['VERIFIER']) page = 1 photos_per_page = 500 all_photos = [] stop_next = False while True: print '\r%d'%len(all_photos),
def maps(loc1, loc2): bing_maps_key = "PUT_KEY_HERE" r = requests.get( 'http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0=' + loc1 + '&wp.1=' + loc2 + '&key=' + bing_maps_key) r_dict = r.json() route_obj = r_dict["resourceSets"][0]["resources"][0] route_dir = route_obj["routeLegs"][0]["itineraryItems"] directions_list = [] i = -1 for r_instr in route_dir: i += 1 dir_obj = {} r_text = r_instr["instruction"]["text"] dir_obj["coords"] = "(" + str( r_instr["maneuverPoint"]["coordinates"][0]) + ", " + str( r_instr["maneuverPoint"]["coordinates"][1]) + ")" # get hints try: dir_obj["hint"] = r_instr["hints"][1]["text"] + "." except: dir_obj["hint"] = "" # FLICKR api_key = "PUT_FLICKR_KEY_HERE" api_secret = "PUT_FLICKR_SECRET_HERE" flickr = FlickrAPI(api_key, api_secret, '/') auth_props = flickr.get_authentication_tokens() auth_url = auth_props['auth_url'] oauth_token = auth_props['oauth_token'] oauth_token_secret = auth_props['oauth_token_secret'] photo_json = flickr.get('flickr.photos.search', params={ 'api_key': api_key, 'lat': r_instr["maneuverPoint"]["coordinates"][0], 'lon': r_instr["maneuverPoint"]["coordinates"][1], 'radius': '0.01' }) photos = photo_json['photos']['photo'] photo = random.choice(photos) flickr_image_url = 'https://farm' + str( photo['farm']) + '.staticflickr.com/' + str( photo['server']) + '/' + str( photo['id']) + '_' + photo['secret'] + '.jpg' # PROJECT OXFORD oxford_key = "PUT_KEY_HERE" headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': oxford_key, } params = urllib.urlencode({ # Request parameters 'visualFeatures': 'All', }) try: conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/vision/v1/analyses?%s" % params, '{ "Url":"' + flickr_image_url + '"}', headers) ox_response = conn.getresponse() ox_data = ox_response.read() ox_json = json.loads(ox_data) #print(ox_data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) # combine directions + descriptions try: if ox_json["categories"][0]["name"] != "others_": r_text = r_text + " near this " + ox_json["categories"][0][ "name"] #print flickr_image_url else: pass except: #print "program failed because of oxford. IMAGE URL \n" #print flickr_image_url #print "OXFORD RESPONSE: \n" #print ox_data pass r_text = r_text + ". " r_text = r_text.replace("_", " ") r_text = r_text.replace("abstract", "landmark") r_text = r_text.replace("outdoor", "outdoor area") r_text = r_text.replace(" .", ".") print r_text dir_obj["r_text"] = r_text dir_obj["url"] = flickr_image_url directions_list.append(dir_obj) #return json.dumps(directions_list) return render_template("maps.html", my_list=directions_list)
def maps(loc1,loc2): bing_maps_key = "PUT_KEY_HERE" r = requests.get('http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0='+loc1+'&wp.1='+loc2+'&key='+bing_maps_key) r_dict = r.json() route_obj = r_dict["resourceSets"][0]["resources"][0] route_dir = route_obj["routeLegs"][0]["itineraryItems"] directions_list = [] i = -1 for r_instr in route_dir: i += 1 dir_obj = {} r_text = r_instr["instruction"]["text"] dir_obj["coords"] = "("+str(r_instr["maneuverPoint"]["coordinates"][0]) + ", "+str(r_instr["maneuverPoint"]["coordinates"][1])+")" # get hints try: dir_obj["hint"] = r_instr["hints"][1]["text"]+"." except: dir_obj["hint"] = "" # FLICKR api_key = "PUT_FLICKR_KEY_HERE" api_secret = "PUT_FLICKR_SECRET_HERE" flickr = FlickrAPI(api_key, api_secret, '/') auth_props = flickr.get_authentication_tokens() auth_url = auth_props['auth_url'] oauth_token = auth_props['oauth_token'] oauth_token_secret = auth_props['oauth_token_secret'] photo_json = flickr.get('flickr.photos.search', params={'api_key':api_key, 'lat': r_instr["maneuverPoint"]["coordinates"][0], 'lon': r_instr["maneuverPoint"]["coordinates"][1], 'radius': '0.01'}) photos = photo_json['photos']['photo'] photo = random.choice(photos) flickr_image_url = 'https://farm' + str(photo['farm']) + '.staticflickr.com/' + str(photo['server']) + '/' + str(photo['id']) + '_' + photo['secret'] + '.jpg' # PROJECT OXFORD oxford_key = "PUT_KEY_HERE" headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': oxford_key, } params = urllib.urlencode({ # Request parameters 'visualFeatures': 'All', }) try: conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/vision/v1/analyses?%s" % params, '{ "Url":"'+flickr_image_url+'"}',headers) ox_response = conn.getresponse() ox_data = ox_response.read() ox_json = json.loads(ox_data) #print(ox_data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) # combine directions + descriptions try: if ox_json["categories"][0]["name"] != "others_": r_text = r_text + " near this " + ox_json["categories"][0]["name"] #print flickr_image_url else: pass except: #print "program failed because of oxford. IMAGE URL \n" #print flickr_image_url #print "OXFORD RESPONSE: \n" #print ox_data pass r_text = r_text +". " r_text = r_text.replace("_"," ") r_text = r_text.replace("abstract","landmark") r_text = r_text.replace("outdoor","outdoor area") r_text = r_text.replace(" .",".") print r_text dir_obj["r_text"] = r_text dir_obj["url"] = flickr_image_url directions_list.append(dir_obj) #return json.dumps(directions_list) return render_template("maps.html",my_list = directions_list)