Package flickrapi :: Class FlickrAPI
[hide private]
[frames] | no frames]

Class FlickrAPI

source code

object --+
         |
        FlickrAPI

Encapsulates Flickr functionality.

Example usage:

flickr = flickrapi.FlickrAPI(api_key)
photos = flickr.photos_search(user_id='73509078@N00', per_page='10')
sets = flickr.photosets_getList(user_id='73509078@N00')
Instance Methods [hide private]
 
__init__(self, api_key, secret=None, username=None, token=None, format='etree', store_token=True, cache=False)
Construct a new FlickrAPI instance for a given API key and secret.
source code
 
__repr__(self)
Returns a string representation of this object.
source code
 
__str__(self)
Returns a string representation of this object.
source code
 
trait_names(self)
Returns a list of method names as supported by the Flickr API.
source code
 
parse_xmlnode(self, rest_xml)
Parses a REST XML response from Flickr into an XMLNode object.
source code
 
parse_etree(self, rest_xml)
Parses a REST XML response from Flickr into an ElementTree object.
source code
 
sign(self, dictionary)
Calculate the flickr signature for a set of params.
source code
 
encode_and_sign(self, dictionary)
URL encodes the data in the dictionary, and signs it using the given secret, if a secret was given.
source code
 
__getattr__(self, attrib)
Handle all the regular Flickr API calls.
source code
 
__supply_defaults(self, args, defaults)
Returns a new dictionary containing args, augmented with defaults from defaults.
source code
 
__flickr_call(self, **kwargs)
Performs a Flickr API call with the given arguments.
source code
 
__wrap_in_parser(self, wrapped_method, parse_format, *args, **kwargs)
Wraps a method call in a parser.
source code
 
auth_url(self, perms, frob)
Return the authorization URL to get a token.
source code
 
web_login_url(self, perms)
Returns the web login URL to forward web users to.
source code
 
__extract_upload_response_format(self, kwargs)
Returns the response format given in kwargs['format'], or the default format if there is no such key.
source code
 
upload(self, filename, callback=None, **kwargs)
Upload a file to flickr.
source code
 
replace(self, filename, photo_id, callback=None, **kwargs)
Replace an existing photo.
source code
 
__upload_to_form(self, form_url, filename, callback, **kwargs)
Uploads a photo - can be used to either upload a new photo or replace an existing one.
source code
 
__send_multipart(self, url, body, progress_callback=None)
Sends a Multipart object to an URL.
source code
 
validate_frob(self, frob, perms)
Lets the user validate the frob by launching a browser to the Flickr website.
source code
 
get_token_part_one(self, perms='read', auth_callback=None)
Get a token either from the cache, or make a new one from the frob.
source code
 
get_token_part_two(self, (token, frob))
Part two of getting a token, see get_token_part_one(...) for details.
source code
 
get_token(self, frob)
Gets the token given a certain frob.
source code
 
authenticate_console(self, perms='read', auth_callback=None)
Performs the authentication, assuming a console program.
source code
 
__data_walker(self, *args, **kwargs)
Calls 'method' with page=0, page=1 etc.
source code
generator, yields each photo in a single set
walk_set(self, photoset_id, per_page=50, ...)
Other arguments can be passed, as documented in the flickr.photosets.getPhotos API call in the Flickr API documentation, except for page because all pages will be returned eventually.
source code
generator, yields each photo in a search query result
walk(self, user_id=..., tags=..., ...)
Accepts the same parameters as flickr.photos.search API call, except for page because all pages will be returned eventually.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __setattr__, __sizeof__, __subclasshook__

Class Variables [hide private]
  flickr_host = 'api.flickr.com'
  flickr_rest_form = '/services/rest/'
  flickr_auth_form = '/services/auth/'
  flickr_upload_form = '/services/upload/'
  flickr_replace_form = '/services/replace/'
Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, api_key, secret=None, username=None, token=None, format='etree', store_token=True, cache=False)
(Constructor)

source code 

Construct a new FlickrAPI instance for a given API key and secret.

api_key
The API key as obtained from Flickr.
secret
The secret belonging to the API key.
username
Used to identify the appropriate authentication token for a certain user.
token
If you already have an authentication token, you can give it here. It won't be stored on disk by the FlickrAPI instance.
format
The response format. Use either "xmlnode" or "etree" to get a parsed response, or use any response format supported by Flickr to get an unparsed response from method calls. It's also possible to pass the format parameter on individual calls.
store_token
Disables the on-disk token cache if set to False (default is True). Use this to ensure that tokens aren't read nor written to disk, for example in web applications that store tokens in cookies.
cache

Enables in-memory caching of FlickrAPI calls - set to True to use. If you don't want to use the default settings, you can instantiate a cache yourself too:

>>> f = FlickrAPI(api_key='123')
>>> f.cache = SimpleCache(timeout=5, max_entries=100)
Overrides: object.__init__

__repr__(self)
(Representation operator)

source code 
Returns a string representation of this object.
Overrides: object.__repr__

__str__(self)
(Informal representation operator)

source code 
Returns a string representation of this object.
Overrides: object.__str__

trait_names(self)

source code 
Returns a list of method names as supported by the Flickr API. Used for tab completion in IPython.

parse_xmlnode(self, rest_xml)

source code 
Parses a REST XML response from Flickr into an XMLNode object.
Decorators:
  • @rest_parser('xmlnode')

parse_etree(self, rest_xml)

source code 
Parses a REST XML response from Flickr into an ElementTree object.
Decorators:
  • @rest_parser('etree')

sign(self, dictionary)

source code 

Calculate the flickr signature for a set of params.

data
a hash of all the params and values to be hashed, e.g. {"api_key":"AAAA", "auth_token":"TTTT", "key": u"value".encode('utf-8')}

__getattr__(self, attrib)
(Qualification operator)

source code 

Handle all the regular Flickr API calls.

Example:

flickr.auth_getFrob(api_key="AAAAAA")
etree = flickr.photos_getInfo(photo_id='1234')
etree = flickr.photos_getInfo(photo_id='1234', format='etree')
xmlnode = flickr.photos_getInfo(photo_id='1234', format='xmlnode')
json = flickr.photos_getInfo(photo_id='1234', format='json')

__supply_defaults(self, args, defaults)

source code 

Returns a new dictionary containing args, augmented with defaults from defaults.

Defaults can be overridden, or completely removed by setting the appropriate value in args to None.

>>> f = FlickrAPI('123')
>>> f._FlickrAPI__supply_defaults(
...  {'foo': 'bar', 'baz': None, 'token': None},
...  {'baz': 'foobar', 'room': 'door'})
{'foo': 'bar', 'room': 'door'}

__flickr_call(self, **kwargs)

source code 

Performs a Flickr API call with the given arguments. The method name itself should be passed as the 'method' parameter.

Returns the unparsed data from Flickr:

data = self.__flickr_call(method='flickr.photos.getInfo',
    photo_id='123', format='rest')

__wrap_in_parser(self, wrapped_method, parse_format, *args, **kwargs)

source code 

Wraps a method call in a parser.

The parser will be looked up by the parse_format specifier. If there is a parser and kwargs['format'] is set, it's set to rest, and the response of the method is parsed before it's returned.

auth_url(self, perms, frob)

source code 

Return the authorization URL to get a token.

This is the URL the app will launch a browser toward if it needs a new token.

perms
"read", "write", or "delete"
frob
picked up from an earlier call to FlickrAPI.auth_getFrob()

web_login_url(self, perms)

source code 

Returns the web login URL to forward web users to.

perms
"read", "write", or "delete"

__extract_upload_response_format(self, kwargs)

source code 

Returns the response format given in kwargs['format'], or the default format if there is no such key.

If kwargs contains 'format', it is removed from kwargs.

If the format isn't compatible with Flickr's upload response type, a FlickrError exception is raised.

upload(self, filename, callback=None, **kwargs)

source code 

Upload a file to flickr.

Be extra careful you spell the parameters correctly, or you will get a rather cryptic "Invalid Signature" error on the upload!

Supported parameters:

filename
name of a file to upload
callback
method that gets progress reports
title
title of the photo
description
description a.k.a. caption of the photo
tags
space-delimited list of tags, '''tag1 tag2 "long tag"'''
is_public
"1" or "0" for a public resp. private photo
is_friend
"1" or "0" whether friends can see the photo while it's marked as private
is_family
"1" or "0" whether family can see the photo while it's marked as private
content_type
Set to "1" for Photo, "2" for Screenshot, or "3" for Other.
hidden
Set to "1" to keep the photo in global search results, "2" to hide from public searches.
format
The response format. You can only choose between the parsed responses or 'rest' for plain REST.

The callback method should take two parameters: def callback(progress, done)

Progress is a number between 0 and 100, and done is a boolean that's true only when the upload is done.

replace(self, filename, photo_id, callback=None, **kwargs)

source code 

Replace an existing photo.

Supported parameters:

filename
name of a file to upload
photo_id
the ID of the photo to replace
callback
method that gets progress reports
format
The response format. You can only choose between the parsed responses or 'rest' for plain REST. Defaults to the format passed to the constructor.

The callback parameter has the same semantics as described in the upload function.

__upload_to_form(self, form_url, filename, callback, **kwargs)

source code 

Uploads a photo - can be used to either upload a new photo or replace an existing one.

form_url must be either FlickrAPI.flickr_replace_form or FlickrAPI.flickr_upload_form.

__send_multipart(self, url, body, progress_callback=None)

source code 

Sends a Multipart object to an URL.

Returns the resulting unparsed XML from Flickr.

get_token_part_one(self, perms='read', auth_callback=None)

source code 

Get a token either from the cache, or make a new one from the frob.

This first attempts to find a token in the user's token cache on disk. If that token is present and valid, it is returned by the method.

If that fails (or if the token is no longer valid based on flickr.auth.checkToken) a new frob is acquired. If an auth_callback method has been specified it will be called. Otherwise the frob is validated by having the user log into flickr (with a browser).

To get a proper token, follow these steps:
  • Store the result value of this method call
  • Give the user a way to signal the program that he/she has authorized it, for example show a button that can be pressed.
  • Wait for the user to signal the program that the authorization was performed, but only if there was no cached token.
  • Call flickrapi.get_token_part_two(...) and pass it the result value you stored.

The newly minted token is then cached locally for the next run.

perms
"read", "write", or "delete"
auth_callback

method to be called if authorization is needed. When not passed, self.validate_frob(...) is called. You can call this method yourself from the callback method too.

If authorization should be blocked, pass auth_callback=False.

The auth_callback method should take (frob, perms) as parameters.

An example:

(token, frob) = flickr.get_token_part_one(perms='write')
if not token:
    raw_input("Press ENTER after you authorized this program")
flickr.get_token_part_two((token, frob))

Also take a look at authenticate_console(perms).

get_token(self, frob)

source code 
Gets the token given a certain frob. Used by get_token_part_two and by the web authentication method.

authenticate_console(self, perms='read', auth_callback=None)

source code 

Performs the authentication, assuming a console program.

Gets the token, if needed starts the browser and waits for the user to press ENTER before continuing.

See get_token_part_one(...) for an explanation of the parameters.

__data_walker(self, *args, **kwargs)

source code 

Calls 'method' with page=0, page=1 etc. until the total number of pages has been visited. Yields the photos returned.

Assumes that method(page=n, **params).findall('*/photos') results in a list of photos, and that the toplevel element of the result contains a 'pages' attribute with the total number of pages.

Decorators:
  • @require_format('etree')

walk_set(self, photoset_id, per_page=50, ...)

source code 

Other arguments can be passed, as documented in the flickr.photosets.getPhotos API call in the Flickr API documentation, except for page because all pages will be returned eventually.

Uses the ElementTree format, incompatible with other formats.

Parameters:
  • photoset_id - the photoset ID
  • per_page - the number of photos that are fetched in one call to Flickr.
Returns: generator, yields each photo in a single set
Decorators:
  • @require_format('etree')

walk(self, user_id=..., tags=..., ...)

source code 

Accepts the same parameters as flickr.photos.search API call, except for page because all pages will be returned eventually.

Also see walk_set.

Returns: generator, yields each photo in a search query result
Decorators:
  • @require_format('etree')