本文整理汇总了Python中flickrapi.FlickrAPI.photosets_getList方法的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI.photosets_getList方法的具体用法?Python FlickrAPI.photosets_getList怎么用?Python FlickrAPI.photosets_getList使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flickrapi.FlickrAPI
的用法示例。
在下文中一共展示了FlickrAPI.photosets_getList方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Shell
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getList [as 别名]
class Shell(cmdln.Cmdln):
r"""ci2 -- the new Code Intel, a tool for working with source code
usage:
${name} SUBCOMMAND [ARGS...]
${name} help SUBCOMMAND
${option_list}
${command_list}
${help_list}
"""
name = "batchr"
#XXX There is a bug in cmdln.py alignment when using this. Leave it off
# until that is fixed.
#helpindent = ' '*4
def _setup(self, opts):
# flickr auth information:
self.flickrAPIKey = os.environ['FLICKR_BATCHR_KEY']
self.flickrSecret = os.environ['FLICKR_BATCHR_SECRET']
try:
gui = opts.gui
except AttributeError: # really wish I could just test "gui" in opts
gui = False
self.progress = progressBar("Flickr Shell", indeterminate=True, gui=gui)
self.progress.update("Logging In...")
# make a new FlickrAPI instance
self.fapi = FlickrAPI(self.flickrAPIKey, self.flickrSecret)
# do the whole whatever-it-takes to get a valid token:
self.token = self.fapi.getToken(browser="Firefox")
def do_listsets(self, subcmd, opts, *args):
"""List set ids and set titles (with substring title matches)"""
self._setup(opts)
kw = dict(api_key=self.flickrAPIKey,
auth_token=self.token)
rsp = self.fapi.photosets_getList(**kw)
self.fapi.testFailure(rsp)
sets = rsp.photosets[0].photoset
for set in sets:
title = set.title[0].elementText
match = True
if args:
match = False
for word in args:
if word.lower() in title.lower():
match = True
break
if match:
print set['id']+':', title, '('+set['photos']+ " photos)"
self.progress.finish()
@cmdln.option("-b", "--base", dest="base",
default="./photos",
help="the directory we want to download to")
@cmdln.option("-F", "--format", dest="format",
help="the file layout format to use within the base directory (default is %(year)s/%(month_name)s/%(size)s/%(id)s.jpg",
default="%(year)s/%(month_name)s/%(size)s/%(id)s.jpg")
@cmdln.option("-f", "--force", action="store_true",
help="force downloads even if files with same name already exist")
@cmdln.option("-y", "--year", dest="year", type='int',
help="the year we want backed up")
@cmdln.option("-m", "--month", dest="month", type='int',
help="the month we want backed up")
@cmdln.option("-s", "--size", dest="size", default='-',
nargs=1,
help="the size we want downloaded: one of: s t m b - o")
@cmdln.option("-t", "--test", action="store_true",
help="Just get the URLs (don't download images) -- implies -l")
@cmdln.option("--tags",
help="Tags (separatead by commas)")
@cmdln.option("-S", "--set",
help="Set id (use listsets command to get them)")
@cmdln.option("-l", "--list", action="store_true",
help="List URLs being downloaded instead of using progress bar")
@cmdln.option("--gui", action="store_true",
help="use Cocoa progress bar on OS X")
def do_download(self, subcmd, opts):
"""Download images based on search criteria (dates, tags, sets)
${cmd_usage}
${cmd_option_list}
Any errors will be printed. Returns the number of errors (i.e.
exit value is 0 if there are no consistency problems).
"""
urls = self._search(opts)
self.progress.reset("Getting Photo Info")
count = 0
downloadeds = 0
bad_ones = []
try:
try:
for (id, url, original_url, date_taken) in urls:
year, month, day = parse_date_taken(date_taken)
month_name = calendar.month_name[month]
size = pretty_size[opts.size]
filename = opts.format % locals()
#.........这里部分代码省略.........
示例2: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getList [as 别名]
#.........这里部分代码省略.........
break
return photos
def getPhotoLocation(self, pid):
"""Returns a string containing location of a photo (in XML)"""
rsp = \
self.fapi.photos_geo_getLocation(api_key=self.__flickrAPIKey,
auth_token=self.token, photo_id=pid)
if self.__testFailure(rsp):
return None
doc = libxml2.parseDoc(rsp.xml)
info = doc.xpathEval('/rsp/photo')[0].serialize()
doc.freeDoc()
return info
def getPhotoLocationPermission(self, pid):
"""Returns a string containing location permision for a photo (in XML)"""
rsp = \
self.fapi.photos_geo_getPerms(api_key=self.__flickrAPIKey,
auth_token=self.token, photo_id=pid)
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):
示例3: FlickrAPI
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getList [as 别名]
# flickr auth information:
flickrSecret = "3fbf7144be7eca28" # shared "secret"
flickrAPIKey = "f8aa9917a9ae5e44a87cae657924f42d" # API key
# make a new FlickrAPI instance
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
# do the whole whatever-it-takes to get a valid token:
token = fapi.getToken(browser="/usr/bin/firefox")
# get my favorites
rsp = fapi.favorites_getList(api_key=flickrAPIKey,auth_token=token)
fapi.testFailure(rsp)
#print 'Photosets: '
print fapi.photosets_getList(api_key=flickrAPIKey, auth_token=token)
rsp = fapi.photosets_getList(api_key=flickrAPIKey, auth_token=token)
fapi.testFailure(rsp)
#print photoSets
#print ', '.join([str(set.title) for set in photoSets])
#person = fapi.flickr_people_getInfo(user_id="tuxmann")
#print person.username
# and print them
if hasattr(rsp.photosets[0], "photoset"):
print 'yeup!'
else:
print 'nope'
for a in rsp.photosets[0].photoset:
示例4: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getList [as 别名]
#.........这里部分代码省略.........
log.info("photo %s removed from set %s", photoId, photosetId)
else:
log.error(rsp.errormsg)
def getBandwidthInfo(self):
log.debug("retrieving bandwidth information")
rsp = self.fapi.people_getUploadStatus(auth_token=self.authtoken)
if not rsp:
log.error("can't retrieve bandwidth information; got error %s",
rsp.errormsg)
return (None,None)
bw = rsp.user[0].bandwidth[0]
log.debug("max bandwidth: %s, bandwidth used: %s", bw['max'], bw['used'])
return (bw['max'], bw['used'])
def getUserId(self):
log.debug("entered")
rsp = self.fapi.auth_checkToken(api_key=flickrAPIKey,
auth_token=self.authtoken)
if not rsp:
log.error("unable to get userid; got error %s", rsp.errormsg)
return None
usr = rsp.auth[0].user[0]
log.info("got NSID %s", usr['nsid'])
#Set self.user_id to this value
self.user_id = usr['nsid']
return usr['nsid']
def getPhotosetList(self):
log.debug("entered")
if self.user_id is "":
self.getUserId() #This will set the value of self.user_id
rsp = self.fapi.photosets_getList(auth_token=self.authtoken,
user_id=self.user_id)
if not rsp:
log.error("error getting photoset list; got error %s", rsp.errormsg)
return []
if not hasattr(rsp.photosets[0], "photoset"):
log.info("no sets found for userid %s", self.user_id)
return []
else:
log.info("%s sets found for userid %s",
len(rsp.photosets[0].photoset), self.user_id)
return rsp.photosets[0].photoset
def parseInfoFromPhoto(self, photo, perms=None):
info = {}
info['id'] = photo['id']
info['title'] = photo['title'].replace('/', '_')
# Some pics don't contain originalformat attribute, so set it to jpg by default.
try:
info['format'] = photo['originalformat']
except KeyError:
info['format'] = 'jpg'
try:
info['dupload'] = photo['dateupload']
except KeyError:
info['dupload'] = '0'
try:
info['dupdate'] = photo['lastupdate']
except KeyError:
info['dupdate'] = '0'
示例5: Importer
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getList [as 别名]
class Importer(object):
def __init__(self):
self.flickr = FlickrAPI(FLICKR_KEY)
def get_photosets(self, username, filename=None):
filename = filename or username+'.json'
if os.path.exists(filename):
print "Looks like we already have information about your photos."
if raw_input("Refresh? (y/n): ").lower().startswith('n'):
return deserialize(open(filename).read())
print "Downloading information about your photos."
if '@' in username:
response = self.flickr.people_findByEmail(find_email=username)
else:
response = self.flickr.people_findByUsername(username=username)
nsid = response[0].get('nsid')
response = self.flickr.photosets_getList(user_id=nsid)
photosets = []
photo_ids = []
for ps in response[0]:
photoset = {'id': ps.get('id'),
'title': ps[0].text,
'description': ps[1].text,
'photos':[]}
photos_response = self.flickr.photosets_getPhotos(photoset_id=photoset['id'],
extras='url_o')
for pxml in photos_response[0]:
photo = {'id':pxml.get('id'),
'title':pxml.get('title')}
photoset['photos'].append(photo)
photo_ids.append(photo['id'])
print photoset['title'],'-',len(photoset['photos']),'photos'
photosets.append(photoset)
# get photos not in photosets
photos_response = self.flickr.photos_search(user_id=nsid, per_page=500)
photoset = {'id':'stream',
'title':'Flickr Stream',
'description':'Photos from my flickr stream',
'photos':[]}
for pxml in response[0]:
photo = {'id':pxml.get('id'),
'title':pxml.get('title')}
if photo['id'] not in photo_ids:
photoset['photos'].append(photo)
photo_ids.append(photo['id'])
if photoset['photos']:
print photoset['title'],'-',len(photoset['photos']),'photos'
photosets.append(photoset)
f = open(filename, "w")
f.write(serialize(photosets))
f.close()
return photosets
def download_images(self, photosets, directory):
print "Downloading your photos"
if not os.path.exists(directory):
os.mkdir(directory)
default = None
for photoset in photosets:
dirpath = os.path.join(directory, photoset['id']+' - '+photoset['title'])
if not os.path.exists(dirpath):
os.mkdir(dirpath)
for photo in photoset['photos']:
filename = os.path.join(dirpath, photo['id']+'.jpg')
if os.path.exists(filename):
if default is None:
print "Photo", photo['id'], "has already been downloaded."
default = raw_input("Download again? (y/n/Y/N) (capital to not ask again): ")
if default == 'n':
default = None
continue
elif default == 'N':
continue
elif default == 'y':
default = None
f = open(filename, 'w')
if not photo.get('url'):
try:
sizes_response = self.flickr.photos_getSizes(photo_id=photo['id'])
except:
print "Failed to download photo:", photo['id'], '... sorry!'
else:
photo['url'] = sizes_response[0][-1].get('source')
if photo.get('url'):
print "Downloading", photo['title'], 'from', photo['url']
remote = urllib2.urlopen(photo['url'])
f.write(remote.read())
f.close()
remote.close()
def upload_images(self, photosets, directory):
client = DivvyshotClient()
for photoset in photosets:
event_data = client.create_event(name=photoset['title'],
#.........这里部分代码省略.........