當前位置: 首頁>>代碼示例>>Python>>正文


Python FlickrAPI.upload方法代碼示例

本文整理匯總了Python中flickrapi.FlickrAPI.upload方法的典型用法代碼示例。如果您正苦於以下問題:Python FlickrAPI.upload方法的具體用法?Python FlickrAPI.upload怎麽用?Python FlickrAPI.upload使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flickrapi.FlickrAPI的用法示例。


在下文中一共展示了FlickrAPI.upload方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: print

# 需要導入模塊: from flickrapi import FlickrAPI [as 別名]
# 或者: from flickrapi.FlickrAPI import upload [as 別名]
from flickrapi import FlickrAPI


class keys:
    apikey = u'a233c66549c9fb5e40a68c1ae156b370'
    apisecret = u'03fbb3ea705fe096'

print('Creating FlickrAPI object')
flickr = FlickrAPI(keys.apikey, keys.apisecret)

# ------------------------------------------------------------------------------
print('Step 1: authenticate')
flickr.authenticate_via_browser(perms='delete')

# ------------------------------------------------------------------------------
print('Step 2: Upload photo')
resp = flickr.upload('tests/photo.jpg', is_public=0, is_friend=0, is_family=0)

from xml.etree import ElementTree as ET
ET.dump(resp)
photo_id = resp.findtext('photoid')

# ------------------------------------------------------------------------------
print('Step 3: Replace photo')
flickr.replace('jaguar.jpg', photo_id=photo_id)

# ------------------------------------------------------------------------------
print('Step 4: Delete photo')
flickr.photos.delete(photo_id=photo_id)
開發者ID:sybrenstuvel,項目名稱:flickrapi,代碼行數:31,代碼來源:oauth_test_4.py

示例2: open

# 需要導入模塊: from flickrapi import FlickrAPI [as 別名]
# 或者: from flickrapi.FlickrAPI import upload [as 別名]
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, \
	title="This is the title", description="This is the description", \
	tags='"tag1 tag2" tag3',\
	is_friend="1", is_public="0", is_family="1")
if rsp == None:
	sys.stderr.write("can't find file\n")
else:
	fapi.testFailure(rsp)

開發者ID:Xirg,項目名稱:flickrfs-old,代碼行數:30,代碼來源:test.py

示例3: __init__

# 需要導入模塊: from flickrapi import FlickrAPI [as 別名]
# 或者: from flickrapi.FlickrAPI import upload [as 別名]
class TransFlickr: 

  extras = "original_format,date_upload,last_update"

  def __init__(self, browserName):
    self.fapi = FlickrAPI(flickrAPIKey, flickrSecret)
    self.user_id = ""
    # proceed with auth
    # TODO use auth.checkToken function if available, 
    # and wait after opening browser.
    print "Authorizing with flickr..."
    log.info("authorizing with flickr...")
    try:
      self.authtoken = self.fapi.getToken(browser=browserName)
    except:
      print ("Can't retrieve token from browser %s" % browserName)
      print ("\tIf you're behind a proxy server,"
             " first set http_proxy environment variable.")
      print "\tPlease close all your browser windows, and try again"
      log.error(format_exc())
      log.error("can't retrieve token from browser %s", browserName)
      sys.exit(-1)
    if self.authtoken == None:
      print "Unable to authorize (reason unknown)"
      log.error('not able to authorize; exiting')
      sys.exit(-1)
        #Add some authorization checks here(?)
    print "Authorization complete."
    log.info('authorization complete')
    
  def uploadfile(self, filepath, taglist, bufData, mode):
    #Set public 4(always), 1(public). Public overwrites f&f.
    public = mode&1
    #Set friends and family 4(always), 2(family), 1(friends).
    friends = mode>>3 & 1
    family = mode>>4 & 1
      #E.g. 745 - 4:No f&f, but 5:public
      #E.g. 754 - 5:friends, but not public
      #E.g. 774 - 7:f&f, but not public

    log.info("uploading file %s", filepath)
    log.info("  data length: %s", len(bufData))
    log.info("  taglist: %s", taglist)
    log.info("  permissions: family %s, friends %s, public %s",
             family, friends, public)
    filename = os.path.splitext(os.path.basename(filepath))[0]
    rsp = self.fapi.upload(filename=filepath, jpegData=bufData,
          title=filename,
          tags=taglist,
          is_public=public and "1" or "0",
          is_friend=friends and "1" or "0",
          is_family=family and "1" or "0")

    if rsp is None:
      log.error("response None from attempt to write file %s", filepath)
      log.error("will attempt recovery...")
      recent_rsp = None
      trytimes = 2
      while(trytimes):
        log.info("sleeping for 3 seconds...")
        time.sleep(3)
        trytimes -= 1
        # Keep on trying to retrieve the recently uploaded photo, till we
        # actually get the information, or the function throws an exception.
        while(recent_rsp is None or not recent_rsp):
          recent_rsp = self.fapi.photos_recentlyUpdated(
              auth_token=self.authtoken, min_date='1', per_page='1')
        
        pic = recent_rsp.photos[0].photo[0]
        log.info('we are looking for %s', filename)
        log.info('most recently updated pic is %s', pic['title'])
        if filename == pic['title']:
          id = pic['id']
          log.info("file %s uploaded with photoid %s", filepath, id)
          return id
      log.error("giving up; upload of %s appears to have failed", filepath)
      return None
    else:
      id = rsp.photoid[0].elementText
      log.info("file %s uploaded with photoid %s", filepath, id)
      return id

  def put2Set(self, set_id, photo_id):
    log.info("uploading photo %s to set id %s", photo_id, set_id)
    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:
#.........這裏部分代碼省略.........
開發者ID:Xirg,項目名稱:flickrfs-old,代碼行數:103,代碼來源:transactions.py

示例4: FlickrCommunicator

# 需要導入模塊: from flickrapi import FlickrAPI [as 別名]
# 或者: from flickrapi.FlickrAPI import upload [as 別名]
class FlickrCommunicator(object):
    """
    The interface to the Flickr API. 
    
    Attributes:
        flickr: The FlickrAPI object that allows communication with Flickr services.
        app_name: The application name to be assoicated with the uploaded images.
    """

    def __init__(self):
        """
        Initializes the link between this app and Flickr API using stored 
        configuration values. Due to the way the Flickr API authorizes, the 
        first time a set of credentials are used on a given system, this must 
        be initialized within a context that allows a browser window to open and
        username and password to be entered.
        """
        
        config_dict = utils.read_config_dict("FlickrCommunicator")
        
        self.flickr = FlickrAPI(config_dict['api_key'], 
                                config_dict['api_secret'])
        
        self.app_name = config_dict['app_name']
        
        (token, frob) = self.flickr.get_token_part_one(perms='write')
        if not token: 
            raw_input("Press ENTER after you authorized this program")
            
        self.flickr.get_token_part_two((token, frob))

    def upload_photo(self, filename, sample_num, timestamp):
        """
        Post an image to the Flickr account.
        
        Args:
            filename: The filename of the image to be uploaded.
            sample_num: The sample number associated with the image.
            timestamp: A string representing the date and time the image was taken.
            
        Returns:
            A shortened url that points to the image uplaoded to Flickr.
        """
        
        #build a description string
        time, date = self._get_timestamp_strings(timestamp)
        
        description = "Sample %d taken at %s on %s" %(sample_num, time, date)
        
        #generate the tag string
        tags = "pellinglab, %s, 'sample %d'" %(self.app_name, sample_num)
        
        #generate the title string
        title = "Pellinglab image. %s" %date
        
        feedback = self.flickr.upload(filename = filename, 
                                    title = title, 
                                    description = description, 
                                    tags = tags)
        
        for elem in feedback:
            photoID = elem.text
        
        return shorturl.url(photoID)

    def _get_timestamp_strings(self, timestamp):
        """
        A helper method to create the time and date strings from a datetime 
        timestamp
        """
        
        months = {
                    1:"Jan",
                    2:"Feb",
                    3:"Mar",
                    4:"Apr",
                    5:"May",
                    6:"Jun",
                    7:"Jul",
                    8:"Aug",
                    9:"Sep",
                    10:"Oct",
                    11:"Nov",
                    12:"Dec"
                 }
        
        time = "%02d:%02d:%02d" %(timestamp.hour, timestamp.minute, timestamp.second)
                
        date = "%s %02d, %d" %(months[timestamp.month], timestamp.day, timestamp.year)
    
        return time, date
開發者ID:CraigBryan,項目名稱:pellinglab_twitter_microscope,代碼行數:93,代碼來源:flickr_receiver.py


注:本文中的flickrapi.FlickrAPI.upload方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。