本文整理汇总了Python中flickrapi.FlickrAPI.photos_getSizes方法的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI.photos_getSizes方法的具体用法?Python FlickrAPI.photos_getSizes怎么用?Python FlickrAPI.photos_getSizes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flickrapi.FlickrAPI
的用法示例。
在下文中一共展示了FlickrAPI.photos_getSizes方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: currentFlickrURL
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [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"
示例2: currentFlickrURL
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [as 别名]
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"
示例3: currentFlickrURL
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [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"
示例4: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [as 别名]
#.........这里部分代码省略.........
return False
return True
def getLicenses(self):
log.debug("started")
rsp = self.fapi.photos_licenses_getInfo()
if not rsp:
log.error("couldn't retrieve licenses; got error %s", rsp.errormsg)
return None
licenseDict = {}
for l in rsp.licenses[0].license:
licenseDict[l['id']] = l['name']
keys = licenseDict.keys()
keys.sort()
sortedLicenseList = []
for k in keys:
# Add tuple of license key, and license value.
sortedLicenseList.append((k, licenseDict[k]))
return sortedLicenseList
def setLicense(self, photoId, license):
log.debug("id: %s, license: %s", photoId, license)
rsp = self.fapi.photos_licenses_setLicense(auth_token=self.authtoken,
photo_id=photoId,
license_id=license)
if not rsp:
log.error("couldn't set license info for photo %s; got error %s",
photoId, rsp.errormsg)
return False
return True
def getPhoto(self, photoId):
log.debug("id: %s", photoId)
rsp = self.fapi.photos_getSizes(auth_token=self.authtoken,
photo_id=photoId)
if not rsp:
log.error("error while trying to retrieve size information"
" for photo %s", photoId)
return None
buf = ""
for a in rsp.sizes[0].size:
if a['label']=='Original':
try:
f = urllib2.urlopen(a['source'])
buf = f.read()
except:
log.error("exception in getPhoto")
log.error(format_exc())
return ""
if not buf:
f = urllib2.urlopen(rsp.sizes[0].size[-1]['source'])
buf = f.read()
return buf
def removePhotofromSet(self, photoId, photosetId):
log.debug("id: %s, setid: %s", photoId, photosetId)
rsp = self.fapi.photosets_removePhoto(auth_token=self.authtoken,
photo_id=photoId,
photoset_id=photosetId)
if rsp:
log.info("photo %s removed from set %s", photoId, photosetId)
else:
log.error(rsp.errormsg)
def getBandwidthInfo(self):
示例5: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [as 别名]
#.........这里部分代码省略.........
"""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
def getOriginalPhoto(self, pid):
"""Returns a URL which is the original photo, if it exists"""
source = None
rsp = self.getPhotoSizes(pid)
if rsp == None:
return None
for s in rsp.sizes[0].size:
if s['label'] == 'Original':
source = s['source']
for s in rsp.sizes[0].size:
if s['label'] == 'Video Original':
source = s['source']
return [source, s['label'] == 'Video Original']
def __downloadReportHook(
self,
count,
blockSize,
totalSize,
):
if not self.__verbose:
return
p = ((100 * count) * blockSize) / totalSize
if p > 100:
p = 100
print '\r %3d %%' % p,
sys.stdout.flush()
def downloadURL(
self,
url,
target,
filename,
verbose=False,
):
"""Saves a photo in a file"""
if self.dryrun:
return
self.__verbose = verbose
tmpfile = '%s/%s.TMP' % (target, filename)
if self.__httplib == 'wget':
cmd = 'wget -q -t 0 -T 120 -w 10 -c -O %s %s' % (tmpfile,
url)
os.system(cmd)
else:
urllib.urlretrieve(url, tmpfile,
reporthook=self.__downloadReportHook)
os.rename(tmpfile, '%s/%s' % (target, filename))
示例6: upload_to_flickr
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [as 别名]
def upload_to_flickr(filename, bits, type):
flickr = FlickrAPI(api_key = api_key, secret = secret, token = token, cache=False)
f = flickr.uploadbits(filename, bits, type)
res = flickr.photos_getSizes(photo_id = f.photoid[0].text)
return res.sizes[0].size[3].attrib['source']
示例7: importFromFlickr
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [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)
#.........这里部分代码省略.........
示例8: remap
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [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
示例9: hasattr
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [as 别名]
#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:
# print "%10s: %s" % (a['id'], a['title'].encode("ascii", "replace"))
print "%10s" % (str(a.title[0].elementText),)
#getPhoto Sizes and urls
rsp = fapi.photos_getSizes(photo_id="43050580", api_key=flickrAPIKey, auth_token=token)
fapi.testFailure(rsp)
for a in rsp.sizes[0].size:
if a['label']=="Large":
print "%s: %20s: %s" % (a['label'], a['source'], a['url'])
import urllib2
f = urllib2.urlopen(a['source'])
newfile = open('newfile', "w")
tempbuf = str(f.read())
print 'converted to string of size: ' + str(long(tempbuf.__len__()))
newfile.write(tempbuf)
print 'wrote to newfile'
newfile.close()
# upload the file foo.jpg
rsp = fapi.upload("/tmp/bsd_vs_tux.jpg", api_key=flickrAPIKey, auth_token=token, \
示例10: Importer
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photos_getSizes [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'],
#.........这里部分代码省略.........