Merge branch 'jupyter'
[mygpo.git] / mygpo / data / flickr.py
blobff393b37abc3ff30cd8fc6d21b003e702893e15a
1 import json
2 import re
3 import requests
5 from django.conf import settings
7 import logging
8 logger = logging.getLogger(__name__)
11 GET_SIZES_TEMPLATE = 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key={api_key}&photo_id={photo_id}&format=json&nojsoncallback=1'
14 def get_photo_sizes(photo_id):
15 """ Returns available sizes for the photo with the given ID
17 Returns a list of dicts containing the following keys
18 * source
19 * url
20 * media
21 * height
22 * width
23 * label
24 """
26 api_key = settings.FLICKR_API_KEY
27 url = GET_SIZES_TEMPLATE.format(api_key=api_key, photo_id=photo_id)
29 try:
30 resp = requests.get(url)
31 except requests.exceptions.RequestException as e:
32 logger.warn('Retrieving Flickr photo sizes failed: %s', str(e))
33 return []
35 resp_obj = resp.json()
37 try:
38 return resp_obj['sizes']['size']
39 except KeyError:
40 return []
43 def get_photo_id(url):
44 """ Returns the Photo ID for a Photo URL
46 >>> get_photo_id('https://farm9.staticflickr.com/8747/12346789012_bf1e234567_b.jpg')
47 '12346789012'
49 >>> get_photo_id('https://www.flickr.com/photos/someuser/12345678901/')
50 '12345678901'
52 """
54 photo_id_re = [
55 'http://.*flickr.com/[^/]+/([^_]+)_.*',
56 'https://.*staticflickr.com/[^/]+/([^_]+)_.*',
57 'https?://.*flickr.com/photos/[^/]+/([^/]+).*',
60 for regex in photo_id_re:
61 match = re.match(regex, url)
62 if match:
63 return match.group(1)
66 def is_flickr_image(url):
67 """ Returns True if the URL represents a Flickr images
69 >>> is_flickr_image('https://farm9.staticflickr.com/8747/12346789012_bf1e234567_b.jpg')
70 True
72 >>> is_flickr_image('http://www.example.com/podcast.mp3')
73 False
75 >>> is_flickr_image(None)
76 False
77 """
79 if url is None:
80 return False
81 return bool(re.search('flickr\.com.*\.(jpg|jpeg|png|gif)', url))
83 def get_display_photo(url, label='Medium'):
84 photo_id = get_photo_id(url)
85 sizes = get_photo_sizes(photo_id)
86 for s in sizes:
87 if s['label'] == label:
88 return s['source']
90 return url