本文整理汇总了Python中flickrapi.FlickrAPI.photos_getInfo方法的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI.photos_getInfo方法的具体用法?Python FlickrAPI.photos_getInfo怎么用?Python FlickrAPI.photos_getInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flickrapi.FlickrAPI
的用法示例。
在下文中一共展示了FlickrAPI.photos_getInfo方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: currentFlickrTitle
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
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: currentFlickrURL
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
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"
示例3: cb
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
def cb():
self.fl_dirty = False
fapi = FlickrAPI(config["api_key"], config["api_secret"])
try:
rsp = fapi.photos_getInfo(apikey=config["api_key"], photo_id=self.image, secret=self.secret)
except Exception, msg:
log.debug("Exception getting image info: %s" % msg)
return {}
示例4: sync_photo
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
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
示例5: currentFlickrURL
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
def currentFlickrURL(kind, linkformat = ""):
'''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 "linkformat" parameter can be omitted, or can be supplied as
either "md" or "html" as long as "kind" is not "Short".
Pass "md" to create a Markdown image reference where the image is linked
back to its Flickr page, or provide "html" to create an HTML
img tag surrounded by an a tag linking to the image's Flickr page.
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')
if linkformat == '':
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"
elif linkformat == '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 etree[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"
elif linkformat == 'html':
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 etree[0]:
if i.attrib['label'] == kind:
jpgurl = i.attrib['source']
photowidth = i.attrib['width']
photoheight = i.attrib['height']
return "<a href='" + photourl + "' title='" + phototitle + "'><img src='" + jpgurl + "' width='" + photowidth + "' height='" + photoheight + "'></a>"
break
# If the size wasn't found.
return "Size not found"
else:
return "Invalid link format requested"
示例6: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
#.........这里部分代码省略.........
if self.__testFailure(rsp):
return None
doc = libxml2.parseDoc(rsp.xml)
info = doc.xpathEval('/rsp/perms')[0].serialize()
doc.freeDoc()
return info
def getPhotosetList(self):
"""Returns a list of photosets for a user"""
rsp = self.fapi.photosets_getList(api_key=self.__flickrAPIKey,
auth_token=self.token, user_id=self.flickrUserId)
if self.__testFailure(rsp):
return None
return rsp.photosets[0].photoset
def getPhotosetInfo(self, pid, method):
"""Returns a string containing information about a photoset (in XML)"""
rsp = method(api_key=self.__flickrAPIKey,
auth_token=self.token, photoset_id=pid)
if self.__testFailure(rsp):
return None
doc = libxml2.parseDoc(rsp.xml)
info = doc.xpathEval('/rsp/photoset')[0].serialize()
doc.freeDoc()
return info
def getPhotoMetadata(self, pid):
"""Returns an array containing containing the photo metadata (as a string), and the format of the photo"""
if self.verbose:
print 'Requesting metadata for photo %s' % pid
rsp = self.fapi.photos_getInfo(api_key=self.__flickrAPIKey,
auth_token=self.token, photo_id=pid)
if self.__testFailure(rsp):
return None
doc = libxml2.parseDoc(rsp.xml)
metadata = doc.xpathEval('/rsp/photo')[0].serialize()
doc.freeDoc()
return [metadata, rsp.photo[0]['originalformat']]
def getPhotoComments(self, pid):
"""Returns an XML string containing the photo comments"""
if self.verbose:
print 'Requesting comments for photo %s' % pid
rsp = \
self.fapi.photos_comments_getList(api_key=self.__flickrAPIKey,
auth_token=self.token, photo_id=pid)
if self.__testFailure(rsp):
return None
doc = libxml2.parseDoc(rsp.xml)
comments = doc.xpathEval('/rsp/comments')[0].serialize()
doc.freeDoc()
return comments
def getPhotoSizes(self, pid):
"""Returns a string with is a list of available sizes for a photo"""
rsp = self.fapi.photos_getSizes(api_key=self.__flickrAPIKey,
auth_token=self.token, photo_id=pid)
if self.__testFailure(rsp):
return None
return rsp
示例7: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
#.........这里部分代码省略.........
rsp = self.fapi.photosets_addPhoto(auth_token=self.authtoken,
photoset_id=set_id, photo_id=photo_id)
if rsp:
log.info("photo uploaded to set")
else:
log.error(rsp.errormsg)
def createSet(self, path, photo_id):
log.info("creating set %s with primary photo %s", path, photo_id)
path, title = os.path.split(path)
rsp = self.fapi.photosets_create(auth_token=self.authtoken,
title=title, primary_photo_id=photo_id)
if rsp:
log.info("created set %s", title)
return rsp.photoset[0]['id']
else:
log.error(rsp.errormsg)
def deleteSet(self, set_id):
log.info("deleting set %s", set_id)
if str(set_id)=="0":
log.info("ignoring attempt to delete set wtih set_id 0 (a locally "
"created set that has not yet acquired an id via uploading")
return
rsp = self.fapi.photosets_delete(auth_token=self.authtoken,
photoset_id=set_id)
if rsp:
log.info("deleted set %s", set_id)
else:
log.error(rsp.errormsg)
def getPhotoInfo(self, photoId):
log.debug("id: %s", photoId)
rsp = self.fapi.photos_getInfo(auth_token=self.authtoken, photo_id=photoId)
if not rsp:
log.error("can't retrieve information about photo %s; got error %s",
photoId, rsp.errormsg)
return None
#XXX: should see if there's some other 'format' option we can fall back to.
try: format = rsp.photo[0]['originalformat']
except KeyError: format = 'jpg'
perm_public = rsp.photo[0].visibility[0]['ispublic']
perm_family = rsp.photo[0].visibility[0]['isfamily']
perm_friend = rsp.photo[0].visibility[0]['isfriend']
if perm_public == '1':
mode = 0755
else:
b_cnt = 4
if perm_family == '1':
b_cnt += 2
if perm_friend == '1':
b_cnt += 1
mode = "07" + str(b_cnt) + "4"
mode = int(mode)
if hasattr(rsp.photo[0],'permissions'):
permcomment = rsp.photo[0].permissions[0]['permcomment']
permaddmeta = rsp.photo[0].permissions[0]['permaddmeta']
else:
permcomment = permaddmeta = [None]
commMeta = '%s%s' % (permcomment,permaddmeta) # Required for chmod.
desc = rsp.photo[0].description[0].elementText
title = rsp.photo[0].title[0].elementText
if hasattr(rsp.photo[0].tags[0], "tag"):
taglist = [ a.elementText for a in rsp.photo[0].tags[0].tag ]
示例8: importFromFlickr
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
def importFromFlickr():
if g.user is None:
return jsonify(result = False, error = "You need to be logged in to import from Flickr")
if not g.user.flickr_auth:
return jsonify(result = False, error = "Your account has not been authenticated with Flickr")
try: # Yes yes, a massive try block, the horror! But almost every single line in here throws an error from FlickrAPI
photoID = request.form.get('photoID')
api_key = os.environ['PARAM1']
api_secret = os.environ['PARAM2']
flickr = FlickrAPI(api_key, api_secret, store_token = False)
# Get original photo's URL
sizes = flickr.photos_getSizes(photo_id = photoID).find('sizes')[-1]
photo_url = sizes.attrib['source']
img_width = int(sizes.attrib['width']) # necessary to correctly scale notes
img_height = int(sizes.attrib['height'])
# Pull a blob of most of the photo's metadata
photo_info = flickr.photos_getInfo(photo_id = photoID).find('photo')
# Check if the person importing this photo actually owns it
flickr_screen_name = photo_info.find('owner').attrib['username']
if flickr_screen_name.lower() != g.user.name.lower():
return jsonify(result = False, error = 'You dog! You don\'t own this photo! %s does. For shame.' % flickr_screen_name)
# Pull photo's title, desc, timestamps from metadata blob
flickr_owner_id = photo_info.find('owner').attrib['nsid'] # used to retrieve views
title = photo_info.find('title').text
desc = photo_info.find('description').text
time_taken = photo_info.find('dates').attrib['taken'] # '2013-06-22 11:16:32' ... wtf?
time_posted = photo_info.find('dates').attrib['posted'] # '1372279163'
# flickr notes are in a 0..500px coordinate space, where 500 maps to max(img_width, img_height)
# brickr notes are normalized to a 0..100 % coordinate space, regardless of image aspect ratio (because I'm smarter)
# flickr notes don't have timestamp info
scale_w = 500 if img_width >= img_height else (500 / img_height * img_width)
scale_h = 500 if img_width < img_height else (500 / img_width * img_height)
notes = []
for note in photo_info.find('notes'):
notes.append({
'user_id': note.attrib['author'],
'screen_name': note.attrib['authorname'],
'text': note.text,
'x': int(note.attrib['x']) / scale_w * 100,
'y': int(note.attrib['y']) / scale_h * 100,
'w': int(note.attrib['w']) / scale_w * 100,
'h': int(note.attrib['h']) / scale_h * 100
})
# Photo tags are easy
tags = []
for tag in photo_info.find('tags'):
if tag.attrib['machine_tag'] != '1': # Ignore ugly automatically created inivisible-to-users tags
tags.append(tag.attrib['raw'])
# Import comments - needs its own Flickr API call
comments = []
if int(photo_info.find('comments').text) > 0:
comment_rsp = flickr.photos_comments_getList(photo_id = photoID).find('comments')
for comment in comment_rsp:
comments.append({
'user_id': comment.attrib.get('author'),
'screen_name': comment.attrib.get('authorname'),
'timestamp': comment.attrib.get('datecreate'),
'iconfarm': comment.attrib.get('iconfarm'),
'iconserver': comment.attrib.get('iconserver'),
'text': comment.text
})
# Import Favorites. These come in at most 50 per request. Another dedicated Flickr API call
favorites = []
favorite_rsp = flickr.photos_getFavorites(photo_id = photoID, per_page = '50').find('photo')
for fav in favorite_rsp:
favorites.append({
'user_id': fav.attrib.get('nsid'),
'screen_name': fav.attrib.get('username'),
'timestamp': fav.attrib.get('favedate'),
'iconfarm': comment.attrib.get('iconfarm'),
'iconserver': comment.attrib.get('iconserver')
})
fav_page_count = int(favorite_rsp.attrib['pages'])
if fav_page_count > 1:
for i in range(2, fav_page_count + 1):
favorite_rsp = flickr.photos_getFavorites(photo_id = photoID, page = str(i), per_page = '50').find('photo')
for fav in favorite_rsp:
favorites.append({
'user_id': fav.attrib['nsid'],
'screen_name': fav.attrib.get('username'),
'timestamp': fav.attrib.get('favedate'),
'iconfarm': comment.attrib.get('iconfarm'),
'iconserver': comment.attrib.get('iconserver')
})
# View count
# There's no direct flickr API to get a photo's view count (weird)
#.........这里部分代码省略.........
示例9: remap
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getInfo [as 别名]
def remap(line):
if flickr.match(line):
global fapi, token
if fapi is None:
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
token = fapi.getToken(browser="lynx")
id = flickr.match(line).group(1)
print " talking to Flickr about: ",id
rsp = fapi.photos_getInfo(api_key=flickrAPIKey,auth_token=token,photo_id=id)
fapi.testFailure(rsp)
description = rsp.photo[0].description[0].elementText
URL = rsp.photo[0].urls[0].url[0].elementText
rsp = fapi.photos_getSizes(api_key=flickrAPIKey,auth_token=token,photo_id=id)
fapi.testFailure(rsp)
localbig = ''
for x in rsp.sizes[0].size:
if x.attrib['label'] == 'Large':
localbig = x.attrib['source'].split('/')[-1]
os.system('curl -o html/photos/%s "%s"' % (localbig, x.attrib['source']))
for x in rsp.sizes[0].size:
#if x.attrib['label'] == 'Square':
if x.attrib['label'] == 'Small':
localpath = x.attrib['source'].split('/')[-1]
big = ''
if localbig != '':
big = '[<a href="photos/%s">local</a>]' % localbig
os.system('curl -o html/photos/%s "%s"' % (localpath, x.attrib['source']))
return '<div class="photo"><a href="%(url)s"><img src="%(src)s" height="%(height)s" width="%(width)s" alt="%(alt)s" /></a><div class="caption">%(caption)s%(localbig)s</div></div>' % \
{'src':'photos/%s'%localpath,#x.attrib['source'],
'height':x.attrib['height'],
'width':x.attrib['width'],
'caption': description,
'url':URL,
'alt':description,
'localbig':big
}
elif localphoto.match(line):
m = localphoto.match(line)
caption = m.group(1)
id = m.group(2)
thumb = id.split('.')[0] + '-thumb.jpeg'
if not os.path.exists(thumb):
cmd = 'convert -resize 240x240 ' + os.path.join(BASE,'photos/'+id) + ' ' + os.path.join(BASE,'photos/'+thumb)
print cmd
os.system(cmd)
## FIXME size probably wrong; figure out real size of
## thumbnail or at least whether its rotated or not
return '<div class="photo"><a href="photos/%s"><img src="photos/%s" height="180" width="240" alt="%s" /></a><div class="caption">%s</div></div>' % (id, thumb, caption, caption)
elif googledoc.match(line):
url = googledoc.match(line).group(1)
print " talking to Google about:",url
html = googledocToHtml(urlopen(url).readlines())
return html
elif resultdoc.match(line):
name = resultdoc.match(line).group(1)
url = resultdoc.match(line).group(2)
print " talking to Google about results:",url
html = resultdocToHtml(urlopen(url).readlines(), url, name)
return html
elif rideschedule.match(line):
year = rideschedule.match(line).group(1).strip()
region = rideschedule.match(line).group(2).strip().lower()
if not year in ridelist.keys():
print " talking to Google about schedule:",year,region
if int(year) > 2010:
ridelist[year] = rideScheduleCsvToRideList(urlopen(PRELIM_RIDE_SCHEDULES[year]).readlines(), year)
else:
ridelist[year] = pre2010rideScheduleCsvToRideList(urlopen(PRELIM_RIDE_SCHEDULES[year]).readlines(), year)
print year,ridelist[year]
officialkey = region.strip().lower() + ':' + year.strip()
if OFFICIAL_RIDE_SCHEDULES.has_key(officialkey):
print " talking to Google about official schedule",year,region,OFFICIAL_RIDE_SCHEDULES[officialkey]
if int(year.strip()) <= 2010:
html = officialRideScheduleToHtml(urlopen(OFFICIAL_RIDE_SCHEDULES[officialkey]).readlines(), ridelist[year], year, region)
else:
html = officialRideListToHtml(ridelist[year], year, region)
else:
print "NO official ride schedule yet for",region,year,officialkey
html = rideListToHtml(ridelist[year], region)
return html
elif membership.match(line):
url = membership.match(line).group(1).strip()
html = membershipToHtml(urlopen(url).readlines())
return html
return line