当前位置: 首页>>代码示例>>Python>>正文


Python FlickrAPI.photosets_getPhotos方法代码示例

本文整理汇总了Python中flickrapi.FlickrAPI.photosets_getPhotos方法的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI.photosets_getPhotos方法的具体用法?Python FlickrAPI.photosets_getPhotos怎么用?Python FlickrAPI.photosets_getPhotos使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flickrapi.FlickrAPI的用法示例。


在下文中一共展示了FlickrAPI.photosets_getPhotos方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sync_set

# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getPhotos [as 别名]
def sync_set(photoset):
	flickr 		= FlickrAPI(API_KEY)
	request 	= flickr.photosets_getPhotos(photoset_id=photoset.flickr_id,extras='last_update')
	photos		= request.find('photoset').findall('photo')
	
	print "Syncing set: %s" %  (smart_str(photoset.title))
	
	updated = False
	
	for photo in reversed(photos):
		photo_id = photo.attrib['id']
		try:
			p = Photo.objects.get(flickr_id = photo_id)
			updated_date = datetime.fromtimestamp(float(photo.attrib['lastupdate']))
			if p.updated_date < updated_date:
				p.title 		= photo.attrib['title']
				p.updated_date 	= updated_date
				
				sync_photo(p)
				
				
		except:
			p = Photo(
				flickr_id 	= photo_id,
				server	 	= int(photo.attrib['server']),
				secret		= photo.attrib['secret'],
				title 		= photo.attrib['title'],
				farm		= int(photo.attrib['farm']),
				added_date	= datetime.now(),
				updated_date= datetime.fromtimestamp(float(photo.attrib['lastupdate'])),
				set			= photoset
			)
			sync_photo(p)
			
			updated = True
			
	return updated
开发者ID:apouche,项目名称:yogikarma,代码行数:39,代码来源:models.py

示例2: __init__

# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getPhotos [as 别名]

#.........这里部分代码省略.........
          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'
    
    info['perms'] = perms
    return info

  def parseInfoFromFullInfo(self, id, fullInfo):
    info = {}
    info['id'] = id
    info['title'] = fullInfo[4]
    info['format'] = fullInfo[0]
    info['dupload'] = fullInfo[10]
    info['dupdate'] = fullInfo[11]
    info['mode'] = fullInfo[1]
    return info

  def getPhotosFromPhotoset(self, photoset_id):
    log.debug("set id: %s", photoset_id)
    photosPermsMap = {}
    # I'm not utilizing the value part of this dictionary. Its arbitrarily
    # set to i.
    for i in range(0,3):
      page = 1
      while True:
        rsp = self.fapi.photosets_getPhotos(auth_token=self.authtoken,
                                            photoset_id=photoset_id, 
                                            extras=self.extras, 
                                            page=str(page),
                                            privacy_filter=str(i))
        if not rsp:
          break
        if not hasattr(rsp.photoset[0], 'photo'):
          log.error("photoset %s doesn't have attribute photo", rsp.photoset[0]['id'])
          break
        for p in rsp.photoset[0].photo:
          photosPermsMap[p] = str(i)
        page += 1
        if page > int(rsp.photoset[0]['pages']): break
      if photosPermsMap: break
    return photosPermsMap
            
  def getPhotoStream(self, user_id):
    log.debug("userid: %s", user_id)
    retList = []
    pageNo = 1
    maxPage = 1
    while pageNo<=maxPage:
      log.info("retreiving page number %s of %s", pageNo, maxPage) 
      rsp = self.fapi.photos_search(auth_token=self.authtoken, 
                                    user_id=user_id, per_page="500", 
                                    page=str(pageNo), extras=self.extras)
      if not rsp:
        log.error("can't retrive photos from your stream; got error %s",
            rsp.errormsg)
        return retList
      if not hasattr(rsp.photos[0], 'photo'):
        log.error("photos.search response doesn't have attribute photos; "
            "returning list acquired so far")
        return retList
      for a in rsp.photos[0].photo:
        retList.append(a)
      maxPage = int(rsp.photos[0]['pages'])
      pageNo = pageNo + 1
    return retList
 
  def getTaggedPhotos(self, tags, user_id=None):
    log.debug("tags: %s user_id: %s", tags, user_id)
    kw = kwdict(auth_token=self.authtoken, tags=tags, tag_mode="all", 
                extras=self.extras, per_page="500")
    if user_id is not None: 
      kw = kwdict(user_id=user_id, **kw)
    rsp = self.fapi.photos_search(**kw)
    log.debug("search for photos with tags %s has been"
              " successfully finished" % tags)
    if not rsp:
      log.error("couldn't search for the photos; got error %s", rsp.errormsg)
      return
    if not hasattr(rsp.photos[0], 'photo'):
      return []
    return rsp.photos[0].photo
开发者ID:Xirg,项目名称:flickrfs-old,代码行数:104,代码来源:transactions.py

示例3: __init__

# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getPhotos [as 别名]

#.........这里部分代码省略.........
        doc.freeDoc()

        return info

    def get_photo_location_permission(self, pid):
        """Returns a string containing location permision for a photo (in
        XML)"""

        rsp = self.fapi.photos_geo_getPerms(api_key=self.flickr_api_key,
                                            auth_token=self.token,
                                            photo_id=pid)
        if self.__test_failure(rsp):
            return None

        doc = libxml2.parseDoc(rsp.xml)
        info = doc.xpathEval('/rsp/perms')[0].serialize()
        doc.freeDoc()
        return info

    def get_photoset_list(self):
        """Returns a list of photosets for a user"""

        rsp = self.fapi.photosets_getList(api_key=self.flickr_api_key,
                                          auth_token=self.token,
                                          user_id=self.flickr_user_id)
        if self.__test_failure(rsp):
            return None

        return rsp.photosets[0].photoset

    def get_photoset_photos(self, pid):
        """Returns a list of photos in a photosets"""

        rsp = self.fapi.photosets_getPhotos(api_key=self.flickr_api_key,
                                            auth_token=self.token,
                                            user_id=self.flickr_user_id,
                                            photoset_id=pid)

        if self.__test_failure(rsp):
            return None

        return rsp.photoset[0].photo

    def get_photoset_info(self, pid, method):
        """Returns a string containing information about a photoset (in XML)"""

        rsp = method(api_key=self.flickr_api_key,
                     auth_token=self.token,
                     photoset_id=pid)

        if self.__test_failure(rsp):
            return None

        doc = libxml2.parseDoc(rsp.xml)
        info = doc.xpathEval('/rsp/photoset')[0].serialize()
        doc.freeDoc()

        return info

    def get_photo_metadata(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
开发者ID:l0b0,项目名称:unflickr,代码行数:69,代码来源:unflickr.py

示例4: Importer

# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import photosets_getPhotos [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'],
#.........这里部分代码省略.........
开发者ID:pcardune,项目名称:paulo.flickrimport,代码行数:103,代码来源:shell.py


注:本文中的flickrapi.FlickrAPI.photosets_getPhotos方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。