This repository was archived by the owner on Feb 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbandcamp.py
More file actions
1151 lines (905 loc) · 29.4 KB
/
Copy pathbandcamp.py
File metadata and controls
1151 lines (905 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python2.4
#
# Copyright 2007 The Python-Bandcamp Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''A library that provides a Python interface to the Bandcamp API'''
__author__ = 'eric@hardlycode.com'
__version__ = '0.0.1'
import base64
import calendar
import datetime
import httplib
import os
import rfc822
import sys
import tempfile
import textwrap
import time
import calendar
import urllib
import urllib2
import urlparse
import gzip
import StringIO
try:
# Python >= 2.6
import json as simplejson
except ImportError:
try:
# Python < 2.6
import simplejson
except ImportError:
try:
# Google App Engine
from django.utils import simplejson
except ImportError:
raise ImportError, "Unable to load a json library"
# parse_qsl moved to urlparse module in v2.6
try:
from urlparse import parse_qsl, parse_qs
except ImportError:
from cgi import parse_qsl, parse_qs
try:
from hashlib import md5
except ImportError:
from md5 import md5
import oauth2 as oauth
# A singleton representing a lazily instantiated FileCache.
DEFAULT_CACHE = object()
class BandcampError(Exception):
'''Base class for Bandcamp errors'''
@property
def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]
class Band(object):
'''A class representing the Band structure used by the bandcamp API.
The Band structure esposes the following properties:
band.name
band.subdomain
band.url
band.id
'''
def __init__(self,
name=None,
subdomain=None,
url=None,
id=None):
'''An object to hold a Bandcamp band.
This class is normally instantiated by the bandcamp.Api class.
Args:
name:
The name of the band.
subdomain:
The subdomain of the band.
url:
The bandcamp url of the band.
id:
The unique id of the band in the bandcamp api.
'''
self.name = name
self.subdomain = subdomain
self.url = url
self.id = id
def GetName(self):
'''Get the name of this band.'''
return self._name
def _SetName(self, name):
'''Set the name of this band.'''
self._name = name
name = property(GetName, _SetName, doc='The name of this band.')
def GetSubdomain(self):
'''Get the subdomain of this band for bandcamp url.'''
return self._subdomain
def _SetSubdomain(self, subdomain):
'''Set the subdomain of this band for bandcamp url.'''
self._subdomain = subdomain
subdomain = property(GetSubdomain, _SetSubdomain, doc='The subdomain for this band on bandcamp.')
def GetUrl(self):
'''Get the url of this band for bandcamp.'''
return self._url
def _SetUrl(self, url):
'''Set the url of this band for bandcamp.'''
self._url = url
url = property(GetUrl, _SetUrl, doc='The url for this band on bandcamp.')
def GetId(self):
'''Get the unique id of this band'''
return self._id
def _SetId(self, id):
'''Set the unique id of this band.'''
self._id = id
id = property(GetId, _SetId, doc='The unique id for this band.')
def AsJsonString(self):
'''A JSON string representation of this bandcamp.Band instance.
Returns:
A JSON string representation of this bandcamp.Band instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this bandcamp.Band instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this bandcamp.Band instance
'''
data = {}
if self.name:
data['name'] = self.name
if self.subdomain:
data['subdomain'] = self.subdomain
if self.url:
data['url'] = self.url
if self.id:
data['id'] = self.id
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the bandcamp API
Returns:
A bandcamp.Band instance
'''
return Band(name=data.get('name', None),
subdomain=data.get('subdomain', None),
url=data.get('url', None),
id=data.get('band_id', None))
class Album(object):
'''A class representing the Album structure used by the bandcamp API.
The Album structure exposes the following properties:
album.id
album.band_id
album.title
album.release_date
album.downloadable
album.url
album.tracks
album.about
album.credits
album.small_art_url
album.large_art_url
album.artist
'''
def __init__(self,
id=None,
band_id=None,
title=None,
release_date=None,
downloadable=None,
url=None,
tracks=None,
about=None,
credits=None,
small_art_url=None,
large_art_url=None,
artist=None):
self._id = id
self._band_id = band_id
self._title = title
self._release_date = release_date
self._downloadable = downloadable
self._url = url
self._tracks = tracks
self._about = about
self._credits = credits
self._small_art_url = small_art_url
self._large_art_url = large_art_url
self._artist = artist
def GetId(self):
'''Get the unique id of this album.'''
return self._id
def _SetId(self, id):
'''Set the unique id of this album.'''
self._id = id
id = property(GetId, _SetId, doc='The unique id of this album.')
def GetBandId(self):
'''Get the unqiue band id of this album.'''
return self._band_id
def _SetBandId(self, band_id):
'''Set the unique band id of this album.'''
self._band_id = band_id
band_id = property(GetBandId, _SetBandId, doc='The unique id of the band who created this album.')
def GetTitle(self):
'''Get the title of this album'''
return self._title
def _SetTitle(self, title):
'''Set the title of this album.'''
self._title = title
title = property(GetTitle, _SetTitle, doc='The title of this album.')
def GetReleaseDate(self):
'''Get the date this album was released.'''
return self._release_date
def _SetReleaseDate(self, release_date):
'''Set the date this album was released.'''
self._release_date = release_date
release_date = property(GetReleaseDate, _SetReleaseDate, doc='The date this album was released.')
def GetDownloadable(self):
'''Get whether or not this album is downloadable. 1 = free, 2 = paid, None = not downloadable'''
return self._downloadable
def _SetDownloadable(self, downloadable):
'''Set whether or not this album is downloadable'''
self._downloadable = downloadable
downloadable = property(GetDownloadable, _SetDownloadable, doc='Determines if album is downloadable')
def GetUrl(self):
'''Get the url of this album.'''
return self._url
def _SetUrl(self, url):
'''Set the url of this album.'''
self._url = url
url = property(GetUrl, _SetUrl, doc='The url of this album.')
def GetTracks(self):
'''Get the tracks for this album.'''
return self._tracks
def _SetTracks(self, tracks):
'''Set the tracks for this album.'''
self._tracks = tracks
tracks = property(GetTracks, _SetTracks, doc='The tracks on this album.')
def GetAbout(self):
'''Get the about info for this album.'''
return self._about
def _SetAbout(self, about):
'''Set the about info for this album.'''
about = property(GetAbout, _SetAbout, doc='The about info for this album.')
def GetCredits(self):
'''Get the credits for this album.'''
return self._credits
def _SetCredits(self, credits):
'''Set the credits for this album.'''
self._credits = credits
credits = property(GetCredits, _SetCredits, doc='The credits for this album.')
def GetSmallArtUrl(self):
'''Get the small album art. 100x100'''
return self._small_art_url
def _SetSmallArtUrl(self, small_art_url):
'''Set the small album art for this album.'''
self._small_art_url = small_art_url
small_art_url = property(GetSmallArtUrl, _SetSmallArtUrl, doc='The small album art url. Image size: 100x100')
def GetLargeArtUrl(self):
'''Get the small album art. 350x350'''
return self.large_art_url
def _SetLargeArtUrl(self, large_art_url):
'''Set the small album art for this album.'''
self.large_art_url = large_art_url
large_art_url = property(GetLargeArtUrl, _SetLargeArtUrl, doc='The large album art url. Image size: 350x350')
def GetArtist(self):
'''Get the album art artist, if different than band's name.'''
return self._artist
def _SetArtist(self, artist):
'''Set the album art artist.'''
self._artist = artist
artist = property(GetArtist, _SetArtist, doc='The album art artist, if different than the band\'s name.')
def AsJsonString(self):
'''A JSON string representation of this bandcamp.Album instance.
Returns:
A JSON string representation of this bandcamp.Album instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this bandcamp.Album instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this bandcamp.Album instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.band_id:
data['band_id'] = self.band_id
if self.title:
data['title'] = self.title
if self.release_date:
data['release_date'] = self.release_date
if self.downloadable:
data['downloadable'] = self.downloadable
if self.url:
data['url'] = self.url
if self.tracks:
data['tracks'] = self.tracks
if self.about:
data['about'] = self.about
if self.credits:
data['credits'] = self.credits
if self.small_art_url:
data['small_art_url'] = self.small_art_url
if self.large_art_url:
data['large_art_url'] = self.large_art_url
if self.artist:
data['artist'] = self.artist
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the bandcamp API
Returns:
A bandcamp.Album instance
'''
# need to convert json tracks to tracks
tracks = [Track.NewFromJsonDict(x) for x in data['tracks']]
return Album(id=data.get("album_id", None),
band_id=data.get("band_id", None),
title=data.get("title", None),
release_date=data.get("release_date", None),
downloadable=data.get("downloadable", None),
url=data.get("url", None),
tracks=tracks,
about=data.get("about", None),
credits=data.get("credits", None),
small_art_url=data.get("small_art_url", None),
large_art_url=data.get("large_art_url", None),
artist=data.get("artist", None))
class Track(object):
'''A class representing the Track structure used by the bandcamp API.
The Track structure exposes the following properties:
track.id
track.album_id
track.band_id
track.number
track.title
track.about
track.credits
track.streaming_url
track.duration
track.downloadable
track.url
track.lyrics
'''
def __init__(self,
id=None,
album_id=None,
band_id=None,
number=None,
title=None,
about=None,
credits=None,
streaming_url=None,
duration=None,
downloadable=None,
url=None,
lyrics=None):
self.id = id
self.album_id = album_id
self.band_id = band_id
self.number = number
self.title = title
self.about = about
self.credits = credits
self.streaming_url = streaming_url
self.duration = duration
self.downloadable = downloadable
self.url = url
self.lyrics = lyrics
def GetId(self):
'''Get the unique id of this track.'''
return self._id
def _SetId(self, id):
'''Set the unique id of this track.'''
id = property(GetId, _SetId, doc='The unique id of this track.')
def GetAlbumId(self):
'''Get the album id of this track.'''
return self._album_id
def _SetAlbumId(self, album_id):
'''Set the album id of this track.'''
self._album_id = album_id
album_id = property(GetAlbumId, _SetAlbumId, doc='The album id of this track.')
def GetBandId(self):
'''Get the band id of this track.'''
return self._band_id
def _SetBandId(self, band_id):
'''Set the band id of this track.'''
self._band_id = band_id
band_id = property(GetBandId, _SetBandId, doc='The band id of this track.')
def GetNumber(self):
'''Get the track number of this track.'''
return self._number
def _SetNumber(self, number):
'''Set the track number of this track.'''
self._number = number
number = property(GetNumber, _SetNumber, doc='The track number of this track.')
def GetTitle(self):
'''Get the title of this track.'''
return self._title
def _SetTitle(self, title):
'''Set the title of this track.'''
self._title = title
title = property(GetTitle, _SetTitle, doc='The title of this track.')
def GetAbout(self):
'''Get the about info for this track.'''
return self._about
def _SetAbout(self, about):
'''Set the about info for this track.'''
about = property(GetAbout, _SetAbout, doc='The about info for this track.')
def GetCredits(self):
'''Get the credits for this track.'''
return self._credits
def _SetCredits(self, credits):
'''Set the credits for this track.'''
self._credits = credits
credits = property(GetCredits, _SetCredits, doc='The credits for this track.')
def GetStreamingUrl(self):
'''Get streaming url for this track.'''
return self._streaming_url
def _SetStreamingUrl(self, streaming_url):
'''Set streaming url for this track.'''
self._streaming_url = streaming_url
streaming_url = property(GetStreamingUrl, _SetStreamingUrl, doc='The streaming url for this track.')
def GetDuration(self):
'''Get the duration of this track.'''
return self._duration
def _SetDuration(self, duration):
'''Set the duration of this track.'''
self._duration = duration
duration = property(GetDuration, _SetDuration, doc='The duration of this track, in seconds (float)')
def GetDownloadable(self):
'''Get whether or not this track is downloadable.'''
return self._downloadable
def _SetDownloadable(self, downloadable):
'''Set whether or not this track is downloadable'''
self._downloadable = downloadable
downloadable = property(GetDownloadable, _SetDownloadable, doc='Determines if track is downloadable. 1 = free, 2 = paid, None = not downloadable')
def GetUrl(self):
'''Get the url of this track.'''
return self._url
def _SetUrl(self, url):
'''Set the url of this track.'''
self._url = url
url = property(GetUrl, _SetUrl, doc='The url of this track.')
def GetLyrics(self):
'''Get the lyrics of this track.'''
return self._lyrics
def _SetLyrics(self, lyrics):
'''Set the lyrics of this track.'''
self._lyrics = lyrics
lyrics = property(GetLyrics, _SetLyrics, doc='The lyrics of this track.')
def AsJsonString(self):
'''A JSON string representation of this bandcamp.Track instance.
Returns:
A JSON string representation of this bandcamp.Track instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this bandcamp.Track instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this bandcamp.Track instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.album_id:
data['album_id'] = self.album_id
if self.band_id:
data['band_id'] = self.band_id
if self.number:
data['number'] = self.number
if self.title:
data['title'] = self.title
if self.about:
data['about'] = self.about
if self.credits:
data['credits'] = self.credits
if self.streaming_url:
data['streaming_url'] = self.streaming_url
if self.duration:
data['duration'] = self.duration
if self.downloadable:
data['downloadable'] = self.downloadable
if self.url:
data['url'] = self.url
if self.lyrics:
data['lyrics'] = self.lyrics
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the bandcamp API
Returns:
A bandcamp.Track instance
'''
return Track(id=data.get("track_id", None),
album_id=data.get("album_id", None),
band_id=data.get("band_id", None),
number=data.get("number", None),
title=data.get("title", None),
about=data.get("about", None),
credits=data.get("credits", None),
streaming_url=data.get("streaming_url", None),
duration=data.get("duration", None),
downloadable=data.get("downloadable", None),
url=data.get("url", None),
lyrics=data.get("lyrics", None))
class Api(object):
'''A python interface into the Bandcamp API.
By default, the Api caches results for 1 minute.
Example usage:
To create an instance of the bandcamp.Api class:
>>> import bandcamp
>>> api = bandcamp.Api(key)
To fetch a band:
>>> band = api.GetBand(band_id)
>>> print band
Included Methods:
api.GetBand(band_id, band_subdomain, band_url)
api.GetAlbum(album_id)
api.GetTrack(track_id)
'''
DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
_API_REALM = 'Bandcamp API'
def __init__(self,
developer_key=None,
cache_timeout=DEFAULT_CACHE_TIMEOUT,
cache=DEFAULT_CACHE,
base_url=None,
debugHTTP=False):
'''Instantiate a new bandcamp.Api object.
Args:
key:
Your Bandcamp developer key.
cache:
The cache instance to use. Defaults to DEFAULT_CACHE.
Use None to disable caching. [Optional]
debugHTTP:
Set to True to enable deboug output from urllib2 when performing
any HTTP requests. Defaults to False. [Optional]
'''
self.SetCache(cache)
self._urllib = urllib2
self._cache_timeout = cache_timeout
self._debugHTTP = debugHTTP
#self._InitializeUserAgent()
self._InitializeDefaultParameters()
if base_url is None:
self.base_url = 'https://api.bandcamp.com/api/'
else:
self.base_url = base_url
if developer_key is None:
raise BandcampError('Bandcamp requires a developer key for all API access. \
Please email support@bandcamp.com with your name and contact email to get access.')
self.SetCredentials(developer_key)
def SetCredentials(self,
developer_key=None):
'''Set the developer key for this instance
Args:
key:
The developer key of the bancamp account.
'''
self._developer_key = developer_key
self._default_params['key'] = self._developer_key
def ClearCredentials(self):
'''Clear the any credentials for this instance.'''
self._developer_key = None
self._default_params['key'] = None
def GetBand(self,
band_id=None,
band_subdomain=None,
band_url=None):
'''Fetch the bandcamp.Band for the given band_id.
Must provide one of the three arguments.
Args:
band_id:
The band id you want to fetch. [Optional]
band_subdomain:
The band subdomain you want to fetch. [Optional]
band_url:
The band url you want to fetch. [Optional]
Returns:
A bandcamp.Band instance
'''
if band_id is None and band_subdomain is None and band_url is None:
raise BandcampError('GetBand requires at least one of the three arguments: band_id, band_subdomain, band_url.')
parameters = {}
if band_id:
parameters['band_id'] = band_id
elif band_subdomain:
parameters['band_url'] = band_subdomain
elif band_url:
parameters['band_url'] = band_url
url = '%s/band/1/info' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
return Band.NewFromJsonDict(data)
def GetDiscography(self,
band_id=None,
band_subdomain=None,
band_url=None):
'''Fetch the '''
if band_id is None and band_subdomain is None and band_url is None:
raise BandcampError('GetDiscography requires at least one of the three arguments: band_id, band_subdomain, band_url.')
parameters = {}
if band_id:
parameters['band_id'] = band_id
elif band_subdomain:
parameters['band_url'] = band_subdomain
elif band_url:
parameters['band_url'] = band_url
url = '%s/band/1/discography' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForBandcampError(data)
results = []
for x in data['discography']:
if x['track_id']:
results.append(Track.NewFromJsonDict(x))
if x['album_id']:
results.append(Album.NewFromJsonDict(x))
# Return built list of discography
return results
def GetAlbum(self, album_id):
'''Fetch the bandcamp.Album for the given album_id.
Args:
album_id:
The album id you want to fetch.
Returns:
A bandcamp.Album instance
'''
parameters = {}
parameters['album_id'] = album_id
url = '%s/album/1/info' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForBandcampError(data)
return Album.NewFromJsonDict(data)
def GetTrack(self, track_id):
'''Fetch the bandcamp.Track for the given track_id.
Args:
track_id:
The track id you want to fetch.
Returns:
A bandcamp.Track instance
'''
parameters = {}
parameters['track_id'] = track_id
url = '%s/track/1/info' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForBandcampError(data)
return Track.NewFromJsonDict(data)
def SetCache(self, cache):
'''Override the default cache. Set to None to prevent caching.
Args:
cache:
An instance that supports the same API as the bandcamp._FileCache
'''
if cache == DEFAULT_CACHE:
self._cache = _FileCache()
else:
self._cache = cache
def SetCacheTimeout(self, cache_timeout):
'''Override the default cache timeout.
Args:
cache_timeout:
Time, in seconds, that response should be reused.
'''
self._cache_timeout = cache_timeout
def SetUrllib(self, urllib):
'''Override the default urllib implmentation.
Args:
urllib:
An instance that supporst the same API as the urllib2 module
'''
self._urllib = urllib
def _InitializeDefaultParameters(self):
self._default_params = {}
def _CheckForBandcampError(self, data):
'''Raises a BandcampError if bandcamp returns an error message.
Args:
data:
A python dict created from the Bandcamp json response
Raises:
BandcampError wrapping the bandcamp error message if one exists.
'''
# Bandcamp errors are relatively unlikely, so it is faster
# to check first, rather than try and catch the exception.
if 'error' in data:
raise BandcampError(data['error'])
def _FetchUrl(self,
url,
post_data=None,
parameters=None,
no_cache=None):
'''Fetch a URL, optional caching for a sepcified time.
Args:
url:
The URL to retrieve
post_data:
A dict of (str, unicode) key/value pairs.
If set, POST will be used [Optional]
parameters:
A dict whose key/value pairs should be encoded
and added to the query string. [Optional]
no_cache:
If true, overrides the cache on the current request.
Returns:
A string containing the body of the response.
'''
# Build the extra parameteres dict
extra_params = {}
if self._default_params:
extra_params.update(self._default_params)
if parameters:
extra_params.update(parameters)
http_method = "GET"
if post_data:
http_method = "POST"
_debug = 0
if self._debugHTTP:
_debug = 1
http_handler = self._urllib.HTTPHandler(debuglevel=_debug)
https_handler = self._urllib.HTTPSHandler(debuglevel=_debug)
opener = self._urllib.OpenerDirector()
opener.add_handler(http_handler)
opener.add_handler(https_handler)
url = self._BuildUrl(url, extra_params=extra_params)
encoded_post_data = self._EncodePostData(post_data)
# Open and return the URL immediately if we're not going to cache
if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
response = opener.open(url, encoded_ost_data)
url_data = self._DecompressGzippedResponse(response)
opener.close()
else:
# Unique keys are a combination of the url and the developer key
if self._developer_key:
key = self._developer_key + ':' + url
else:
key = url
# See if it has been cached before
last_cached = self._cache.GetCachedTime(key)
# If the cached version is outdated then fetch another and store it
if not last_cached or time.time() >= last_cached + self._cache_timeout:
try:
response = opener.open(url, encoded_post_data)
url_data = self._DecompressGzippedResponse(response)
self._cache.Set(key, url_data)
except urllib2.HTTPError, e:
print e
opener.close()
else:
url_data = self._cache.Get(key)
# Alwyas return the latest version
return url_data
def _BuildUrl(self, url, path_elements=None, extra_params=None):
# Break url into consituent parts
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
# Add any additional path elements to the path
if path_elements:
#Filter out the path elements that have a value of None
p = [i for i in path_elemnts if i]
if not path.endswith('/'):
path += '/'
path += '/'.join(p)
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
# Add it to the existing query