Source

copelco / lib / copelco / apps / flickr / api / __init__.py

import time
import json
import urllib
import urllib2
import urlparse
import logging

import oauth2 as oauth


__all__ = ('Flickr',)


logger = logging.getLogger('flickr')
logging.basicConfig(level=logging.DEBUG)


class Flickr(object):
    """
    Simple Flickr API wrapper
    """

    url = 'http://api.flickr.com/services/rest/'

    def __init__(self, key, secret):
        self._consumer_key = key
        self._consumer_secret = secret

    def _call(self, **kwargs):
        """
        Call Flickr REST service and parse JSON response
        """
        settings = {
            'format': 'json',
            'api_key': self._consumer_key,
            'nojsoncallback': 1,
        }
        kwargs.update(settings)
        logger.debug('REST call: {0}'.format(kwargs))
        response = urllib2.urlopen(self.url, urllib.urlencode(kwargs))
        data = json.loads(response.read())
        return data

    def search(self, **kwargs):
        """
        Helper method to call flickr.photos.search
        """
        return self._call(method='flickr.photos.search', **kwargs)

    def user_photos(self, username, **kwargs):
        """
        Iterate through user photos, page by page
        """
        if 'per_page' not in kwargs:
            kwargs['per_page'] = 50
        page, pages = 1, 1
        logger.debug('Fetching page 1 of user photos')
        while page <= pages:
            if page > 1:
                msg = 'Fetching page {0} of {1} of user photos'
                logger.debug(msg.format(page, pages))
            kwargs['page'] = page
            response = self.search(user_id=username, **kwargs)
            pages = response['photos']['pages']
            for photo in response['photos']['photo']:
                yield photo
            page += 1

    def get_nsid(self, username):
        """
        Return a user's NSID, given their username
        """
        response = self._call(method='flickr.people.findByUsername',
                              username=username)
        return response['user']['nsid']