本文整理汇总了Python中flickrapi.FlickrAPI.getToken方法的典型用法代码示例。如果您正苦于以下问题:Python FlickrAPI.getToken方法的具体用法?Python FlickrAPI.getToken怎么用?Python FlickrAPI.getToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flickrapi.FlickrAPI
的用法示例。
在下文中一共展示了FlickrAPI.getToken方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FlickrAPI
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
#!/usr/bin/env python
#test comment
import sys
from flickrapi import FlickrAPI
# Autenticazione
flickrAPIKey = "ea9b8730af07cd76f6dc4fde27744b74" # API key
flickrSecret = "45dfeeb5abec1ff9" # shared "secret"
gruppo='[email protected]'
# crea una istanza di FlickrAPI
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
# ottieni un token valido
token = fapi.getToken(browser="firefox", perms="write")
rsp = fapi.auth_checkToken(api_key=flickrAPIKey, auth_token=token)
fapi.testFailure(rsp)
#grabba tutte le foto con il group id specificato
rsp = fapi.groups_pools_getPhotos(auth_token=token,api_key=flickrAPIKey,group_id=gruppo)
fapi.testFailure(rsp)
for a in rsp.photos[0].photo:
rsp = fapi.groups_pools_remove(api_key=flickrAPIKey,photo_id=a['id'],auth_token=token,group_id=gruppo)
fapi.testFailure(rsp,exit=0)
示例2: Shell
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [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()
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [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:
#.........这里部分代码省略.........
示例4: FlickrAPI
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
import sys
from flickrapi import FlickrAPI
import wx
# Autenticazione
flickrAPIKey = "ea9b8730af07cd76f6dc4fde27744b74" # API key
flickrSecret = "45dfeeb5abec1ff9" # shared "secret"
# crea una istanza di FlickrAPI
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
# ottieni un token valido
if sys.platform == 'win32':
token = fapi.getToken(browser="C:\\Progra~1\\Intern~1\\iexplore.exe", perms="write")
else:
token = fapi.getToken(browser="firefox", perms="write")
rsp = fapi.auth_checkToken(api_key=flickrAPIKey, auth_token=token)
fapi.noExitTestFailure(rsp)
user_id = rsp.auth[0].user[0]['nsid']
#################sux
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1CHOICE1, wxID_FRAME1CHOICE2, wxID_FRAME1INTESTAZIONE,
wxID_FRAME1OKBUTTON, wxID_FRAME1STATUSBAR1,
] = [wx.NewId() for _init_ctrls in range(6)]
示例5: remap
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [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
示例6: open
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
sys.path.insert(0, "/home/mike/python")
from flickrapi import FlickrAPI
from flickr import MikeFlickr
flickrAPIKey = open("/home/mike/flickr.key", "r").read()
flickrSecret = open("/home/mike/flickr.secret", "r").read()
fapi = None
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
if len(sys.argv) < 2:
print "usage: %s JPEG [JPEG]" % sys.argv[0]
sys.exit(-1)
token = fapi.getToken(browser="lynx") ##,perms="delete")
mikeapi = MikeFlickr(fapi, flickrAPIKey, token)
## methods
def userinput(prompt):
rtn = ""
while len(rtn) == 0:
rtn = raw_input(prompt).strip()
return rtn
##
## now, upload everything on the command line (unless we have already
## backed it up)
示例7: open
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
sys.path.insert(0, "/home/mike/python")
from flickrapi import FlickrAPI
from flickr import MikeFlickr
flickrAPIKey = open("/home/mike/flickr.key", "r").read()
flickrSecret = open("/home/mike/flickr.secret", "r").read()
fapi = None
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
if len(sys.argv) < 2:
print "usage: %s JPEG [JPEG]" % sys.argv[0]
sys.exit(-1)
token = fapi.getToken(browser="lynx")
mikeapi = MikeFlickr(fapi, flickrAPIKey, token)
##
## first get info from Flickr on what I've already backed up, by the
## "mikebackup" tag
##
existing = mikeapi.imagesByTag("mikebackup", privateOnly=True)
print "got", len(existing), "existing photos."
names = map(lambda x: x[1].lower(), existing)
# print names[:10]
##
## now, upload everything on the command line (unless we have already
示例8: FlickrAPI
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
#!/usr/bin/python
import sys
from flickrapi import FlickrAPI
# 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"):
示例9: FlickrAPI
# 需要导入模块: from flickrapi import FlickrAPI [as 别名]
# 或者: from flickrapi.FlickrAPI import getToken [as 别名]
#!/usr/bin/python
import sys
from flickrapi import FlickrAPI
# flickr auth information:
flickrAPIKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # API key
flickrSecret = "yyyyyyyyyyyyyyyy" # shared "secret"
# make a new FlickrAPI instance
fapi = FlickrAPI(flickrAPIKey, flickrSecret)
# do the whole whatever-it-takes to get a valid token:
token = fapi.getToken(browser="firefox")
# get my favorites
rsp = fapi.favorites_getList(api_key=flickrAPIKey,auth_token=token)
fapi.testFailure(rsp)
# and print them
for a in rsp.photos[0].photo:
print "%10s: %s" % (a['id'], a['title'].encode("ascii", "replace"))
# upload the file foo.jpg
#fp = file("foo.jpg", "rb")
#data = fp.read()
#fp.close()
#rsp = fapi.upload(jpegData=data, api_key=flickrAPIKey, auth_token=token, \
#rsp = fapi.upload(filename="foo.jpg", api_key=flickrAPIKey, auth_token=token, \
# title="This is the title", description="This is the description", \
# tags="tag1 tag2 tag3",\