parsers.py 2.16 KB
Newer Older
1
# Tweepy
2
3
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
4

5
6
from tweepy.models import ModelFactory
from tweepy.utils import import_simplejson
Josh Roesslein's avatar
Josh Roesslein committed
7

8

9
class Parser(object):
10

11
    def parse(self, method, payload):
12
13
14
15
16
17
18
        """
        Parse the response payload and return the result.
        Returns a tuple that contains the result data and the cursors
        (or None if not present).
        """
        raise NotImplementedError

Joshua's avatar
Joshua committed
19
20
21
22
23
24
25
26
    def parse_error(self, payload):
        """
        Parse the error message from payload.
        If unable to parse the message, throw an exception
        and default error message will be used.
        """
        raise NotImplementedError

27
28
29

class JSONParser(Parser):

30
    payload_format = 'json'
31

32
33
34
    def __init__(self):
        self.json_lib = import_simplejson()

35
    def parse(self, method, payload):
36
37
38
39
40
        try:
            json = self.json_lib.loads(payload)
        except Exception, e:
            raise TweepError('Failed to parse JSON payload: %s' % e)

41
        if isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
42
43
44
45
            cursors = json['previous_cursor'], json['next_cursor']
            return json, cursors
        else:
            return json
46

Joshua's avatar
Joshua committed
47
48
49
    def parse_error(self, payload):
        return self.json_lib.loads(payload)['error']

50

51
class ModelParser(JSONParser):
Josh Roesslein's avatar
Josh Roesslein committed
52

53
    def __init__(self, model_factory=None):
54
        JSONParser.__init__(self)
55
        self.model_factory = model_factory or ModelFactory
Josh Roesslein's avatar
Josh Roesslein committed
56

57
    def parse(self, method, payload):
58
        try:
59
60
            if method.payload_type is None: return
            model = getattr(self.model_factory, method.payload_type)
61
62
        except AttributeError:
            raise TweepError('No model for this payload type: %s' % method.payload_type)
63

64
        json = JSONParser.parse(self, method, payload)
65
66
67
68
        if isinstance(json, tuple):
            json, cursors = json
        else:
            cursors = None
69

70
71
        if method.payload_list:
            result = model.parse_list(method.api, json)
72
        else:
73
            result = model.parse(method.api, json)
74
75
76

        if cursors:
            return result, cursors
Josh Roesslein's avatar
Josh Roesslein committed
77
        else:
78
            return result
Josh Roesslein's avatar
Josh Roesslein committed
79