2 Access a freedb service from Python.
15 def __init__(self
, cddb_server
= 'http://freedb.freedb.org/~cddb/cddb.cgi',
16 app
= "PyCDDB", version
= __version__
):
17 self
.cddb_server
= cddb_server
18 self
.user
= getpass
.getuser()
19 self
.host
= socket
.gethostname()
21 self
.version
= version
31 elif self
.code
== 200:
32 return "Found exact match"
33 elif self
.code
== 202:
34 return "No match found"
35 elif self
.code
== 210:
37 elif self
.code
== 211:
38 return "Found inexact matches"
39 elif self
.code
== 401:
40 return "Specified CDDB entry not found"
41 elif self
.code
== 402:
43 elif self
.code
== 403:
44 return "Database entry is corrupt"
45 elif self
.code
== 409:
48 def query(self
, discid
):
51 self
.track_offset
= map(string
.atoi
, string
.split(discid
)[2:-1])
52 self
.disc_length
= string
.atoi(string
.split(discid
)[-1:][0]) * 75
53 query
= urllib
.quote_plus(string
.rstrip(discid
))
54 url
= "%s?cmd=cddb+query+%s&hello=%s+%s+%s+%s&proto=%d" % \
55 (self
.cddb_server
, query
, self
.user
, self
.host
, self
.app
,
56 self
.version
, self
.protocol
)
57 response
= urllib
.urlopen(url
)
58 header
= response
.readline()
59 if re
.match("[0-9]+.*", header
):
60 self
.code
= string
.atoi(string
.split(header
, ' ', 1)[0])
61 if self
.code
== 200: # Exact match
62 info
= string
.split(header
, ' ', 3)
63 result
.append( { 'category': info
[1], 'disc_id': info
[2], 'title': info
[3] } )
64 elif self
.code
== 210 or self
.code
== 211: # Multiple exact mattches or inexact match
65 line
= string
.rstrip(response
.readline())
67 info
= string
.split(line
, ' ', 2)
68 result
.append( { 'category': info
[0], 'disc_id': info
[1], 'title': info
[2] } )
69 line
= string
.rstrip(response
.readline())
73 def read(self
, query_item
):
75 url
= "%s?cmd=cddb+read+%s+%s&hello=%s+%s+%s+%s&proto=%d" % \
76 (self
.cddb_server
, query_item
['category'], query_item
['disc_id'],
77 self
.user
, self
.host
, self
.app
, self
.version
, self
.protocol
)
78 response
= urllib
.urlopen(url
)
79 header
= response
.readline()
80 self
.code
= string
.atoi(string
.split(header
, ' ', 1)[0])
82 re_indexed_key
= re
.compile("([^=0123456789]+)([0-9]+)=(.*)")
83 re_key
= re
.compile("([^=]+)=(.*)")
84 for line
in response
.readlines():
85 line
= string
.rstrip(line
)
86 m
= re_indexed_key
.match(line
)
88 (key
, index
, data
) = m
.groups()
89 if result
.has_key(key
):
90 result
[key
].append(data
)
93 result
[key
].append(data
)
95 m
= re_key
.match(line
)
97 (key
, data
) = m
.groups()