Skip to content

Commit

Permalink
handle malformed XML API responses
Browse files Browse the repository at this point in the history
  • Loading branch information
sampsyo committed Sep 16, 2010
1 parent 59232fb commit 5843908
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ Version History

0.2
Fail safely when file is too short.
Safely handle malformed XML returned from the API.

0.1
Initial release.
Expand Down
13 changes: 12 additions & 1 deletion lastfp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import urllib
import urllib2
import xml.etree.ElementTree as etree
from xml.parsers.expat import ExpatError
import os
import threading
import time
Expand Down Expand Up @@ -196,16 +197,26 @@ def match(apikey, pcmiter, samplerate, duration, channels=2, metadata=None):
return metadata_query(fpid, apikey)

class APIError(FingerprintError):
# Raised for errors returned by the API service.
def __init__(self, code, message):
super(APIError, self).__init__(message)
self.code = code
self.message = message
class CommunicationError(FingerprintError):
# Raised when we can't communicate with the API service.
pass
def parse_metadata(xml):
"""Given an XML document (string) returned from metadata_query(),
parse the response into a list of track info dicts. May raise an
APIError if the lookup fails.
"""
root = etree.fromstring(xml)
try:
root = etree.fromstring(xml)
except ExpatError:
# The Last.fm API occasionally generates malformed XML when its
# includes an illegal character (UTF8-legal but prohibited by
# the XML standard).
raise CommunicationError('malformed XML response')

status = root.attrib['status']
if status == 'failed':
Expand Down

0 comments on commit 5843908

Please sign in to comment.