models.py 4.44 KB
Newer Older
1 2 3 4 5
from utils import *

class Model(object):

    accessible_fields = ['id']
Rocky Duan committed
6 7
    updatable_fields = ['id']
    initializable_fields = ['id']
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    base_url = None
    default_retrieve_params = {}

    DEFAULT_ACTIONS_WITH_ID = ['get', 'put', 'delete']
    DEFAULT_ACTIONS_WITHOUT_ID = ['get_all', 'post']
    DEFAULT_ACTIONS = DEFAULT_ACTIONS_WITH_ID + DEFAULT_ACTIONS_WITHOUT_ID

    def __init__(self, *args, **kwargs):
        self.attributes = extract(kwargs, self.accessible_fields)
        self.retrieved = False

    def __getattr__(self, name):
        if name == 'id':
            return self.attributes.get('id', None)
        try:
            return self.attributes[name]
        except KeyError:
            if self.retrieved or self.id == None:
                raise AttributeError("Field {0} does not exist".format(name))
            self.retrieve()
            return self.__getattr__(name)
    
    def __setattr__(self, name, value):
        if name == 'attributes' or name not in self.accessible_fields:
            super(Model, self).__setattr__(name, value)
        else:
            self.attributes[name] = value

    def __getitem__(self, key):
        if key not in self.accessible_fields:
            raise KeyError("Field {0} does not exist".format(key))
        return self.attributes.get(key)

    def __setitem__(self, key, value):
        if key not in self.accessible_fields:
            raise KeyError("Field {0} does not exist".format(key))
        self.attributes.__setitem__(key, value)

Rocky Duan committed
46 47 48
    def items(self, *args, **kwargs):
        return self.attributes.items(*args, **kwargs)

49 50 51 52 53 54 55 56 57 58 59 60 61 62
    def get(self, *args, **kwargs):
        return self.attributes.get(*args, **kwargs)

    def to_dict(self):
        self.retrieve()
        return self.attributes

    def retrieve(self, *args, **kwargs):
        if not self.retrieved:
            self._retrieve(*args, **kwargs)
            self.retrieved = True
        return self

    def _retrieve(self, *args, **kwargs):
Rocky Duan committed
63
        url = self.url(action='get', params=self.attributes)
64 65 66 67 68 69 70 71 72 73 74 75 76
        response = perform_request('get', url, self.default_retrieve_params)
        self.update_attributes(**response)

    @classmethod
    def find(cls, id):
        return cls(id=id)

    def update_attributes(self, *args, **kwargs):
        for k, v in kwargs.items():
            if k in self.accessible_fields:
                self.__setattr__(k, v)
            else:
                raise AttributeError("Field {0} does not exist".format(k))
Rocky Duan committed
77

Rocky Duan committed
78
    def updatable_attributes(self):
Rocky Duan committed
79 80 81 82
        return extract(self.attributes, self.updatable_fields)

    def initializable_attributes(self):
        return extract(self.attributes, self.initializable_fields)
83
        
Rocky Duan committed
84 85 86 87 88 89 90 91
    @classmethod
    def before_save(cls, instance):
        pass

    @classmethod
    def after_save(cls, instance):
        pass

92
    def save(self):
Rocky Duan committed
93
        self.__class__.before_save(self)
94
        if self.id: # if we have id already, treat this as an update
Rocky Duan committed
95 96
            url = self.url(action='put', params=self.attributes)
            response = perform_request('put', url, self.updatable_attributes())
97
        else: # otherwise, treat this as an insert
Rocky Duan committed
98 99
            url = self.url(action='post', params=self.attributes)
            response = perform_request('post', url, self.initializable_attributes())
100 101
        self.retrieved = True
        self.update_attributes(**response)
Rocky Duan committed
102
        self.__class__.after_save(self)
103

104 105 106 107 108 109
    def delete(self):
        url = self.url(action='delete', params=self.attributes)
        response = perform_request('delete', url)
        self.retrieved = True
        self.update_attributes(**response)

110
    @classmethod
Rocky Duan committed
111 112
    def url_with_id(cls, params={}):
        return cls.base_url + '/' + str(params['id'])
113 114

    @classmethod
Rocky Duan committed
115
    def url_without_id(cls, params={}):
116 117 118
        return cls.base_url

    @classmethod
Rocky Duan committed
119
    def url(cls, action, params={}):
120 121
        if cls.base_url is None:
            raise CommentClientError("Must provide base_url when using default url function")
Rocky Duan committed
122
        if action not in cls.DEFAULT_ACTIONS:
123 124
            raise ValueError("Invalid action {0}. The supported action must be in {1}".format(action, str(cls.DEFAULT_ACTIONS)))
        elif action in cls.DEFAULT_ACTIONS_WITH_ID:
Rocky Duan committed
125 126 127
            try:
                return cls.url_with_id(params)
            except KeyError:
128 129 130
                raise CommentClientError("Cannot perform action {0} without id".format(action))
        else: # action must be in DEFAULT_ACTIONS_WITHOUT_ID now
            return cls.url_without_id()