Index your Flickr Photos in Python
17 November 2007
A friend asked me to look at a broken script that he found online. The script used the Python module for interfacing with the Flickr API. So I thought I would go and give the Flickr API a try.
Flickr is a photo hosting website owned by Yahoo! Like all good web services, Flickr has an Application programming interface. The Python implementation has been created by Beej Jorgensen.
So that's all well and good, but what I can do with it? Well for me, it might be useful to create a webpage that indexes all my flickr sets and photos, especially if I use Flickr more in the future (not too much there yet). I can then share my photos on my own homepage.
If you want to play along, then you need to obtain a flickr API key. Stick it in the scipt at the start (use quote marks of course).
You might also want to use your own flickr user id, you need it in the numeral form, click here to find that out.
Here is the script in a downloadable form (don't forget to rename it to .py).
#!/usr/bin/env python
"""An index of your flickr photos. """
# Add your API key below
API_KEY = None
MY_USER_ID = '43827815@N00'
TEMPLATE = """Content-Type: text/html\n\n
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>My Flickr Photos</title>
</head>
<body>
%(picsets)s
%(pictures)s
</body>
</html>"""
import flickrapi
class FlickrIndex(object):
"""Makes a simple HTML index of your flickr photos."""
def __init__(self,
api_key,
my_user_id = '43827815@N00'):
self.flickr = flickrapi.FlickrAPI(api_key)
self.my_user_id = my_user_id
def print_sets(self):
"""Makes an unordered list of sets."""
sets = self.flickr.photosets_getList(user_id =
self.my_user_id)
setsection = "<h1>My Flickr Sets</h1> \n"
setsection += "<ul> \n"
for i in sets.photosets[0].photoset:
setsection += '<li><a href="' +
'http://www.flickr.com/photos/' + \
self.my_user_id + '/sets/' + i['id']
+ \
'">' + i.title[0].elementText +
'</a></li> \n'
setsection += "</ul>"
return setsection
def print_photos(self):
"""Makes an unordered list of pictures."""
photos = self.flickr.photos_search(user_id =
self.my_user_id)
picsection = "<h1>My Flickr Photos</h1> \n"
picsection += "<ul> \n"
for i in photos.photos[0].photo:
picsection += '<li><a href="' +
'http://www.flickr.com/photos/' + \
self.my_user_id + '/' + i['id'] + \
'">' + i['title'] + '</a></li> \n'
picsection += "</ul> \n"
return picsection
def main():
"""Might as well try to do something if called directly"""
webpage = FlickrIndex(API_KEY, MY_USER_ID)
includes = {'picsets': webpage.print_sets(), \
'pictures' :
webpage.print_photos() }
print TEMPLATE % includes
# start the ball rolling
if __name__ == "__main__":
main()



1 Ciaran says...
Wooo! Thanks Zeth.
Posted at 2:36 p.m. on November 20, 2007