1
2
3 '''Helper functions for the short http://fli.kr/p/... URL notation.
4
5 Photo IDs can be converted to and from Base58 short IDs, and a short
6 URL can be generated from a photo ID.
7
8 The implementation of the encoding and decoding functions is based on
9 the posts by stevefaeembra and Kohichi on
10 http://www.flickr.com/groups/api/discuss/72157616713786392/
11
12 '''
13
14 __all__ = ['encode', 'decode', 'url', 'SHORT_URL']
15
16 ALPHABET = u'123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
17 ALPHALEN = len(ALPHABET)
18 SHORT_URL = u'http://flic.kr/p/%s'
19
20
22 '''encode(photo_id) -> short id
23
24 >>> encode(u'4325695128')
25 u'7Afjsu'
26 >>> encode(u'2811466321')
27 u'5hruZg'
28 '''
29
30 photo_id = int(photo_id)
31
32 encoded = u''
33 while photo_id >= ALPHALEN:
34 div, mod = divmod(photo_id, ALPHALEN)
35 encoded = ALPHABET[mod] + encoded
36 photo_id = int(div)
37
38 encoded = ALPHABET[photo_id] + encoded
39
40 return encoded
41
42
44 '''decode(short id) -> photo id
45
46 >>> decode(u'7Afjsu')
47 u'4325695128'
48 >>> decode(u'5hruZg')
49 u'2811466321'
50 '''
51
52 decoded = 0
53 multi = 1
54
55 for i in xrange(len(short_id)-1, -1, -1):
56 char = short_id[i]
57 index = ALPHABET.index(char)
58 decoded = decoded + multi * index
59 multi = multi * len(ALPHABET)
60
61 return unicode(decoded)
62
63
65 '''url(photo id) -> short url
66
67 >>> url(u'4325695128')
68 u'http://flic.kr/p/7Afjsu'
69 >>> url(u'2811466321')
70 u'http://flic.kr/p/5hruZg'
71 '''
72
73 short_id = encode(photo_id)
74 return SHORT_URL % short_id
75