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.


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:



I wanted to display photos with the following machine tag:


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)

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

<div id="all-photos" class="photos">
  {% for image in Images %}
  {% endfor %}


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.


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:

    $('#all-photos ul li a').lightBox();


Tags: flickr embed api