예제 #1
0
    def dispatch(self, request, *args, **kwargs):
        tokens = request.user.social_auth.get(provider='flickr').tokens
        tokens = dict(urlparse.parse_qsl(tokens.get('access_token')))

        self.flickr_api = FlickrAPI(
            api_key=settings.FLICKR_APP_ID,
            api_secret=settings.FLICKR_API_SECRET,
            oauth_token=tokens.get('oauth_token'),
            oauth_token_secret=tokens.get('oauth_token_secret'))

        return (super(FlickrRequiredMixin,
                      self).dispatch(request, *args, **kwargs))
예제 #2
0
 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)
예제 #3
0
import sys
import tqdm
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
예제 #4
0
파일: app.py 프로젝트: benlowkh/Landmark
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)