Embedding Flickr Photos

May 20, 2011

I wanted to embed photos from flickr onto my website, but only ones that had a particular machine tag on. The website was written in Django, so required a python api. I chose to use the api from http://stuvel.eu/flickrapi. I downloaded this and put it into my project source.

Settings

At flickr, I signed up for a new account (I wanted to keep my experiments with site photos separate to my personal photos) and created a non-commercial api key on that account. I then added the following to my settings.py, with the apiKey value as supplied from flickr:

FLICKR_API_KEY = 'apiKey'

Code

I wanted to display photos with the following machine tag:

drumcoder:contest=12345

In my Django view, I added the following code:

import flickrapi

lFlickr = flickrapi.FlickrAPI(settings.FLICKR_API_KEY)
lPictureKey = "12345"
lMachineTag = "drumcoder:contest=%s" % lPictureKey
lPhotos = lFlickr.photos_search(safe_search=1, content_type=1, sort="date-taken-asc", machine_tags=lFlickrMachineTag)
lPhotosNode = lPhotos.getchildren()[0]
lImages = []
for lImage in lPhotosNode.getchildren():
    lId = lImage.attrib['id']
    lServerId = lImage.attrib['server']
    lFarmId = lImage.attrib['farm']
    lSecret = lImage.attrib['secret']
    lImg = '<img class="photo" src="http://farm%s.static.flickr.com/%s/%s_%s_s.jpg"/>' % (lFarmId, lServerId, lId, lSecret)
    lImgTag = '<a href="http://farm%s.static.flickr.com/%s/%s_%s_z.jpg">%s</a>' % (lFarmId, lServerId, lId, lSecret, lImg)
    lImages.append(lImgTag)

I then passed lImages as a template variable, and iterated through the photos in the page:

<div id="all-photos" class="photos">
  <ul>
  {% for image in Images %}
    <li>{{image|safe}}</li>
  {% endfor %}
  </ul>
</div>

Problems

I had a problem with my search returning no results. This appears to be because my new account has yet to be reviewed for safety - on http://www.flickr.com/account there is a blank field against Your safety level. When I added the machine tag to a photo on my existing old account, this was returned back in the HTML.

Lightbox

The script at http://leandrovieira.com/projects/jquery/lightbox/ works well for displaying zoomed pictures.

Include the following in your header:

<link rel="stylesheet" type="text/css" href="/site_media/lightbox/css/jquery.lightbox-0.5.css" media="screen" />
<script type="text/javascript" src="/site_media/lightbox/js/jquery.lightbox-0.5.min.js"></script>

and then run:

$(document).ready(function(){
    $('#all-photos ul li a').lightBox();
  });

References

Tags: flickr embed api