2 # Copyright 2009-2010 Joshua Roesslein
3 # See LICENSE for details.
5 from tweepy.models import ModelFactory
6 from tweepy.utils import import_simplejson
7 from tweepy.error import TweepError
12 def parse(self, method, payload):
14 Parse the response payload and return the result.
15 Returns a tuple that contains the result data and the cursors
16 (or None if not present).
18 raise NotImplementedError
20 def parse_error(self, payload):
22 Parse the error message from payload.
23 If unable to parse the message, throw an exception
24 and default error message will be used.
26 raise NotImplementedError
29 class RawParser(Parser):
34 def parse(self, method, payload):
37 def parse_error(self, payload):
41 class JSONParser(Parser):
43 payload_format = 'json'
46 self.json_lib = import_simplejson()
48 def parse(self, method, payload):
50 json = self.json_lib.loads(payload)
51 except Exception as e:
52 raise TweepError('Failed to parse JSON payload: %s' % e)
54 needsCursors = method.parameters.has_key('cursor')
55 if needsCursors and isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
56 cursors = json['previous_cursor'], json['next_cursor']
61 def parse_error(self, payload):
62 error = self.json_lib.loads(payload)
63 if error.has_key('error'):
66 return error['errors']
69 class ModelParser(JSONParser):
71 def __init__(self, model_factory=None):
72 JSONParser.__init__(self)
73 self.model_factory = model_factory or ModelFactory
75 def parse(self, method, payload):
77 if method.payload_type is None: return
78 model = getattr(self.model_factory, method.payload_type)
79 except AttributeError:
80 raise TweepError('No model for this payload type: %s' % method.payload_type)
82 json = JSONParser.parse(self, method, payload)
83 if isinstance(json, tuple):
88 if method.payload_list:
89 result = model.parse_list(method.api, json)
91 result = model.parse(method.api, json)
94 return result, cursors