本文整理汇总了Python中flickrapi.FlickrAPI类的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI类的具体用法?Python FlickrAPI怎么用?Python FlickrAPI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FlickrAPI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: currentFlickrTitle
def currentFlickrTitle():
'''Return the title of the Flickr image currently showing in the browser.
The function works through Apple Events and supports only the Safari
browser.'''
# Flickr parameters
fuser = 'Flickr username'
key = 'Get key from Flickr'
secret = 'Get secret from Flickr'
# Get the image ID.
try:
imageID = currentFlickrID()
except IndexError:
return "Not a Flickr image"
# Establish the connection with Flickr.
flickr = FlickrAPI(api_key=key, secret=secret)
# Get the title.
etree = flickr.photos_getInfo(photo_id = imageID, format = 'etree')
for i in etree[0]:
if i.tag == 'title':
return i.text
break
# If the size wasn't found.
return "Title not found"
示例2: flickr_auth
def flickr_auth():
# Convert the frob passed back from Flickr's auth system into an auth token.
api_key = os.environ['PARAM1']
api_secret = os.environ['PARAM2']
flickr = FlickrAPI(api_key, api_secret, store_token = False)
token = flickr.get_token(request.values['frob'])
# Retrieve the Flickr screen name associated with the dude that just authenticated
rsp = flickr.auth_checkToken(auth_token = token, format = 'xmlnode')
flickr_screen_name = rsp.auth[0].user[0].attrib['username']
user = session['tmp_flickr_user'];
# Check if authenticated screen name matches screen name entered on account creation
if flickr_screen_name.lower() == user.name.lower():
user.flickr_auth = True
db.session.add(user)
db.session.commit()
flash('You have successfully authenticated your Flickr account. Welcome.')
return redirect(url_for('index')) # Send newly minted user to their Brickr landing page
else:
flash('Your chosen Screen Name does not match the Screen Name you logged into Flickr with! Try this one.')
db.session.rollback()
return redirect(url_for('users.register', next = oid.get_next_url(),
do_flickr_auth = True,
screen_name = flickr_screen_name,
real_name = user.real_name,
email = user.email)) # Send user back to profile creation page
return 'FAILED to Authenticate with Flickr. FAILED. HARD. Call Remi.'
示例3: cb
def cb():
fapi = FlickrAPI(config["api_key"], config["api_secret"])
try:
rsp = fapi.photos_comments_getList(apikey=config["api_key"], photo_id=self.image)
except Exception, msg:
log.debug("Exception getting comments: %s" % msg)
return {}
示例4: run
def run(write_directory, exiv2_file_path, from_date):
"""Fetch all geotagged photos and write exiv2 script for them.
Retrieve all geotagged photos taken since `from_date` to
`write_directory` and write a set of exiv2(1) commands storing
geotags in EXIF to `exiv2_file_path`.
`from_date` is a string YYYY-MM-DD, `write_directory` and
`exiv2_file_path` are valid directory and file names,
respectively.
"""
exiv2_file = open(exiv2_file_path, 'w')
# Start flickring
flickr = FlickrAPI(API_KEY, API_SECRET, format='etree')
# Authorize
(token, frob) = flickr.get_token_part_one(perms='read')
if not token: raw_input('Press ENTER after you authorized this program')
flickr.get_token_part_two((token, frob))
print 'Retrieving list of geotagged photos taken since %s...' % from_date
photos = flickr.photos_getWithGeoData(min_date_taken=from_date).getiterator('photo')
# Retrieve photo to `write_directory`, write exiv2 commands to
# scriptfile.
for photo in photos:
title, url, location = get_photo_data(flickr, photo)
print 'Retrieving photo %s...' % title
filename, headers = urlretrieve(url, os.path.join(write_directory, \
os.path.basename(url)))
write_location_commands(os.path.abspath(filename), location, exiv2_file)
示例5: remove_from_group
def remove_from_group(self, token):
fapi = FlickrAPI(config["api_key"], config["api_secret"], token=token)
try:
rsp = fapi.groups_pools_remove(photo_id=self.image, group_id=config["group_id"])
except Exception, msg:
log.debug("Exception removing from group: %s" % (msg))
return False
示例6: currentFlickrURL
def currentFlickrURL(kind, format = ""):
'''Return a URL for the Flickr image currently showing in the browser.
The string parameter "kind" can be either "Short" or one of the standard
Flickr image sizes: "Original", "Large", "Medium 640", "Medium", "Small",
"Thumbnail", or "Square". If it's Short, the function will return a
flic.kr URL for the image page. If it's one of the others, the function
will return the URL of the image of that size, if available.
The function works through Apple Events and supports only the Safari and
Chrome browsers.'''
# Flickr parameters
fuser = 'Flickr username'
key = 'Get key from Flickr'
secret = 'Get secret from Flickr'
# Make sure we're asking for a legitimate kind.
kind = kind.capitalize()
kinds = ["Short", "Original", "Large", "Medium 640",
"Medium", "Small", "Thumbnail", "Square"]
if kind not in kinds:
return "Not a legitimate kind of URL"
# Get the image ID.
try:
imageID = currentFlickrID()
except IndexError:
return "Not a Flickr image"
# Establish the connection with Flickr.
flickr = FlickrAPI(api_key=key, secret=secret)
# Get the URL.
if kind == "Short":
return shorturl.url(photo_id = imageID)
else:
esizes = flickr.photos_getSizes(photo_id = imageID, format = 'etree')
if format == '':
for i in esizes[0]:
if i.attrib['label'] == kind:
return i.attrib['source']
break
# If the size wasn't found.
return "Size not found"
elif format == 'md':
einfo = flickr.photos_getInfo(photo_id = imageID, format = 'etree')
photourl = einfo.find('photo/urls/url').text
phototitle = einfo.find('photo/title').text
if not phototitle:
phototitle = "Untitled"
for i in esizes[0]:
if i.attrib['label'] == kind:
jpgurl = i.attrib['source']
return "[![" + phototitle + "](" + jpgurl + ")](" + photourl + ")"
break
# If the size wasn't found.
return "Size not found"
示例7: _reload
def _reload(self):
# Here, we grab some stuff from the pool, filter it against what we already have in the
# db table, and make sure that we've got at least 20 items.
fapi = FlickrAPI(config['api_key'], config['api_secret'])
bite_size = 20
ct_checked = 0
ct_added = 0
ct_total = 200 # so long as this is > 0, we're ok.
page = 1
while ct_added < bite_size and ct_checked < ct_total:
log.debug('downloading, starting at: %d' % ct_checked)
try:
rsp = fapi.groups_pools_getphotos(apikey=config['api_key'],
group_id=config['group_id'],
page=page,
per_page=100)
except Exception, msg:
log.debug(msg.args)
return False
log.debug(rsp)
photos = rsp.find('photos')
ct_checked += int(photos.get('perpage'))
ct_total = int(photos.get('total'))
log.debug('got photos %s'%photos)
for photo in photos.getchildren():
# photo_id, date_added == the tuple of a primary key. If it's there, then we skip it.
image = photo.get('id')
log.debug('checking %s'%image)
dt = int(photo.get('dateadded'))
if PseudoPing.get(image=image, dt=dt):
log.debug('already in table')
continue
if Decision.get(image=image, fl_ok=True):
log.debug('already decided good')
continue
if not ImageHistory.get(image=image, dt=dt):
log.debug("adding image history entry, since one doesn't exist yet")
#undone -- concurrency issue here?
#undone -- check dup here?
ih = ImageHistory()
ih.image = image
ih.dt = dt
ih.save()
ImageHistory.commit()
p = PseudoPing()
p.image = image
p.dt = dt
p.owner = photo.get('owner')
p.secret = photo.get('secret')
log.debug('saving')
ct_added += 1
p.save()
if ct_added >= bite_size:
# thinking pulling just a small bite at a time would be better -- keep things fresher.
# rather than sometimes pulling in 100 at a shot.
break
page+=1
示例8: test_authenticate_fail
def test_authenticate_fail(self):
flickr = FlickrAPI(FAKEKEY, FAKESECRET)
try:
(token, frob) = flickr.get_token_part_one(perms='write')
if not token: raw_input("Press ENTER after you authorized this program")
flickr.get_token_part_two((token, frob))
except FlickrError as e:
self.assertEqual(e[0], u'Error: 100: Invalid API Key (Key not found)')
示例9: cb
def cb(self):
# this is the callback point for the flickr auth.
# we'll get a parameter of ?frob=123412341234
# we call flickr.auth.getToken with the frob, and get
# xml with the username, the token, and permissions.
fapi = FlickrAPI(config['api_key'], config['api_secret'])
frob = request.params.get('frob')
if not frob:
return "Invalid Response"
rsp = fapi.auth_getToken(frob=frob)
auth = rsp.find('auth')
if not auth:
return "invalid response from get token"
username = auth.find('user').get('username').encode('ascii','ignore')
token = auth.find('token').text
nsid = auth.find('user').get('nsid')
if not (username and token):
return "Invalid Response from getToken"
user = model.User.get_byNsid(nsid)
if not user:
user = model.User.get_byName(username)
if not user:
user = model.User()
user.username = username
user.nsid = auth.find('user').get('nsid')
user.make_secret()
user.save()
user.nsid = nsid
user.commit()
else:
# people can change usernames, nsids are static.
if user.username != username:
user.username=username
user.commit()
session['user'] = username
session['nsid'] = nsid
session['mod'] = user.check_mod(token)
if session['mod']:
session['token'] = token
session.save()
# Send user back to the page he originally wanted to get to
if session.get('path_before_login'):
path = session['path_before_login']
del(session['path_before_login'])
redirect(url(path))
else:
if session.get('mod'):
redirect(url('/ping/index'))
redirect(url('/profile/bookmarklet'))
示例10: tag
def tag(self, tags, token):
fapi = FlickrAPI(config["api_key"], config["api_secret"], token=token)
if type(tags) == type([]):
tags = ",".join(tags)
try:
rsp = fapi.photos_addTags(photo_id=self.image, tags=tags)
except Exception, msg:
log.debug("Exception adding tags (%s) to %s: %s" % (tags, self.image, msg))
return False
示例11: get_flickr
def get_flickr(API_KEY, SECRET, TOKEN=None):
if TOKEN is None:
flickr = FlickrAPI(API_KEY, SECRET)
(token, frob) = flickr.get_token_part_one(perms='write')
if not token:
raw_input("Press ENTER after you authorized this program")
flickr.get_token_part_two((token, frob))
else:
flickr = FlickrAPI(api_key=API_KEY, secret=SECRET, token=TOKEN)
return flickr
示例12: __init__
def __init__(self, api_key, secret=None, token=None, store_token=False, cache=False, **kwargs):
FlickrAPI.__init__(self, api_key, secret=secret, token=token, store_token=store_token, cache=cache, **kwargs)
# Thread-local HTTPConnection, see __flickr_call
self.thr = ThreadLocal()
if token: return
(token, frob) = self.get_token_part_one(perms='read')
if not token:
print "A browser window should have opened asking you to authorise this program."
raw_input("Press ENTER when you have done so... ")
self.get_token_part_two((token, frob))
示例13: sync_photo
def sync_photo(photo):
flickr = FlickrAPI(API_KEY)
infos = flickr.photos_getInfo(photo_id=photo.flickr_id).find('photo')
exifs = flickr.photos_getExif(photo_id=photo.flickr_id).find('photo').findall('exif')
print "\tSyncing Photo: %s" % smart_str(photo.title)
for exif in exifs:
if exif.attrib['label'] == 'Aperture' and exif.attrib['tag'] == 'FNumber':
photo.aperture = exif.find('clean').text
if exif.attrib['label'] == 'Model' and exif.attrib['tag'] == 'Model':
photo.camera = exif.find('raw').text
if exif.attrib['label'] == 'Exposure' and exif.attrib['tag'] == 'ExposureTime':
photo.exposure = exif.find('raw').text
if exif.attrib['label'] == 'ISO Speed' and exif.attrib['tag'] == 'ISO':
photo.iso = exif.find('raw').text
if exif.attrib['label'] == 'Lens' and exif.attrib['tag'] == 'Lens':
photo.lens = exif.find('raw').text
photo.posted_date = datetime.fromtimestamp(float(infos.find('dates').attrib['posted']))
photo.description = infos.find('description').text
tags = infos.find('tags').findall('tag')
photo.tags.clear() # clear all previous tags if present
#Save photo prior saving the many to many relationship with tags
try:
photo.save()
except:
print '\t\tFail to Save Photo: %s' % smart_str(photo.title)
return photo
for tag in tags:
tag_id = tag.text[0:31]
print '\t\tFound tag: %s' % tag_id
try:
t = Tag.objects.get(pk=tag_id)
photo.tags.add(t)
except:
t = Tag(name=tag.text, raw=tag.attrib['raw'])
t.save()
photo.tags.add(t)
#print '[Flickr] Exif for %s: %s, %s, %s' % (photo.title, photo.lens, photo.iso, photo.posted_date)
return photo
示例14: currentFlickrURL
def currentFlickrURL(kind):
'''Return a URL for the Flickr image currently showing in the browser.
The string parameter "kind" can be either "Short" or one of the
standard Flickr image sizes: "Original", "Large", "Medium 800",
"Medium 640", "Medium", "Small 320", "Small", "Thumbnail", "Large
Square", or "Square". If it's Short, the function will return a
flic.kr URL for the image page. If it's one of the others, the
function will return the URL of the image of that size, if
available.
The function works through Apple Events and supports only the Safari
browser.'''
# Flickr parameters
fuser = 'Flickr username'
key = 'Get key from Flickr'
secret = 'Get secret from Flickr'
# Make sure we're asking for a legitimate kind.
kind = ' '.join([x.capitalize() for x in kind.split()])
kinds = ["Short", "Original", "Large", "Medium 800", "Medium 640",
"Medium", "Small 320", "Small", "Thumbnail",
"Large Square", "Square"]
if kind not in kinds:
return "Not a legitimate kind of URL"
# Get the image ID.
try:
imageID = currentFlickrID()
except IndexError:
return "Not a Flickr image"
# Establish the connection with Flickr.
flickr = FlickrAPI(api_key=key, secret=secret)
# Get the URL.
if kind == "Short":
return shorturl.url(photo_id = imageID)
else:
etree = flickr.photos_getSizes(photo_id = imageID, format = 'etree')
for i in etree[0]:
if i.attrib['label'] == kind:
return i.attrib['source']
break
# If the size wasn't found.
return "Size not found"
示例15: __init__
def __init__(
self,
key,
secret,
httplib=None,
dryrun=False,
verbose=False,
):
"""Instantiates an Offlickr object
An API key is needed, as well as an API secret"""
self.__flickrAPIKey = key
self.__flickrSecret = secret
self.__httplib = httplib
# Get authentication token
# note we must explicitly select the xmlnode parser to be compatible with FlickrAPI 1.2
self.fapi = FlickrAPI(self.__flickrAPIKey, self.__flickrSecret,
format='xmlnode')
(token, frob) = self.fapi.get_token_part_one()
if not token:
raw_input('Press ENTER after you authorized this program')
self.fapi.get_token_part_two((token, frob))
self.token = token
test_login = self.fapi.test_login()
uid = test_login.user[0]['id']
self.flickrUserId = uid
self.dryrun = dryrun
self.verbose = verbose