2 # Copyright 2009-2010 Joshua Roesslein
3 # See LICENSE for details.
5 from __future__ import print_function
7 from tweepy.models import ModelFactory
8 from tweepy.utils import import_simplejson
9 from tweepy.error import TweepError
14 def parse(self, method, payload):
16 Parse the response payload and return the result.
17 Returns a tuple that contains the result data and the cursors
18 (or None if not present).
20 raise NotImplementedError
22 def parse_error(self, payload):
24 Parse the error message from payload.
25 If unable to parse the message, throw an exception
26 and default error message will be used.
28 raise NotImplementedError
31 class RawParser(Parser):
36 def parse(self, method, payload):
39 def parse_error(self, payload):
43 class JSONParser(Parser):
45 payload_format = 'json'
48 self.json_lib = import_simplejson()
50 def parse(self, method, payload):
52 json = self.json_lib.loads(payload)
53 except Exception as e:
54 raise TweepError('Failed to parse JSON payload: %s' % e)
56 needs_cursors = 'cursor' in method.session.params
57 if needs_cursors and isinstance(json, dict):
58 if 'previous_cursor' in json:
59 if 'next_cursor' in json:
60 cursors = json['previous_cursor'], json['next_cursor']
65 def parse_error(self, payload):
66 error = self.json_lib.loads(payload)
67 if error.has_key('error'):
70 return error['errors']
73 class ModelParser(JSONParser):
75 def __init__(self, model_factory=None):
76 JSONParser.__init__(self)
77 self.model_factory = model_factory or ModelFactory
79 def parse(self, method, payload):
81 if method.payload_type is None:
83 model = getattr(self.model_factory, method.payload_type)
84 except AttributeError:
85 raise TweepError('No model for this payload type: '
86 '%s' % method.payload_type)
88 json = JSONParser.parse(self, method, payload)
89 if isinstance(json, tuple):
94 if method.payload_list:
95 result = model.parse_list(method.api, json)
97 result = model.parse(method.api, json)
100 return result, cursors