|
| 1 | +# encoding:utf-8 |
| 2 | +from copy import deepcopy |
| 3 | +import datetime |
| 4 | +import requests |
| 5 | + |
| 6 | +from logging import getLogger |
| 7 | +from schematics.models import Model |
| 8 | +from schematics.types import BooleanType, DateType |
| 9 | +from schematics.types.compound import ListType, DictType, ModelType |
| 10 | + |
| 11 | +logger = getLogger('pipedrive.api') |
| 12 | + |
| 13 | +BASE_URL = 'https://api.pipedrive.com/v1' |
| 14 | + |
| 15 | + |
| 16 | +class PipedriveAPI(object): |
| 17 | + resource_registry = {} |
| 18 | + |
| 19 | + def __init__(self, api_token): |
| 20 | + self.api_token = api_token |
| 21 | + |
| 22 | + def __getattr__(self, item): |
| 23 | + try: |
| 24 | + return PipedriveAPI.resource_registry[item](self) |
| 25 | + except KeyError: |
| 26 | + raise AttributeError('No resource is registered under that name.') |
| 27 | + |
| 28 | + def send_request(self, method, path, params=None, data=None): |
| 29 | + params = params or {} |
| 30 | + params['api_token'] = self.api_token |
| 31 | + url = BASE_URL + path |
| 32 | + try: |
| 33 | + return requests.request(method, url, params=params, data=data) |
| 34 | + except: |
| 35 | + logger.exception("Request failed") |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def register_resource(resource_class): |
| 39 | + PipedriveAPI.resource_registry[ |
| 40 | + resource_class.API_ACESSOR_NAME] = resource_class |
| 41 | + |
| 42 | + |
| 43 | +class BaseResource(object): |
| 44 | + """Common ground for all api resources. |
| 45 | +
|
| 46 | + Attributes: |
| 47 | + API_ACESSOR_NAME(str): The property name that this resource will be |
| 48 | + accessible from the Api object (i.e. "sms" ) api.sms.liist() |
| 49 | + LIST_REQ_PATH(str): The request path component for the list view |
| 50 | + (listing and creation) |
| 51 | + DETAIL_REQ_PATH(str): The request path component for the detail view |
| 52 | + (deletion, updating and detail) |
| 53 | + """ |
| 54 | + |
| 55 | + API_ACESSOR_NAME = '' |
| 56 | + LIST_REQ_PATH = None |
| 57 | + DETAIL_REQ_PATH = None |
| 58 | + |
| 59 | + def __init__(self, api): |
| 60 | + self.api = api |
| 61 | + setattr(self.api, self.API_ACESSOR_NAME, self) |
| 62 | + |
| 63 | + def send_request(self, method, path, params, data): |
| 64 | + response = self.api.send_request(method, path, params, data) |
| 65 | + if 200 <= response.status_code < 400: |
| 66 | + return response |
| 67 | + self.process_error(response) |
| 68 | + |
| 69 | + def process_success(self, data): |
| 70 | + pass |
| 71 | + |
| 72 | + def process_error(self, response): |
| 73 | + pass |
| 74 | + |
| 75 | + def _create(self, params=None, data=None): |
| 76 | + return self.send_request('POST', self.LIST_REQ_PATH, params, data) |
| 77 | + |
| 78 | + def _list(self, params=None, data=None): |
| 79 | + return self.send_request('GET', self.LIST_REQ_PATH, params, data) |
| 80 | + |
| 81 | + def _delete(self, resource_ids, params=None, data=None): |
| 82 | + url = self.DETAIL_REQ_PATH % resource_ids |
| 83 | + return self.send_request('DELETE', url, params=None, data=None) |
| 84 | + |
| 85 | + def _update(self, resource_ids, params=None, data=None): |
| 86 | + url = self.DETAIL_REQ_PATH % resource_ids |
| 87 | + return self.send_request('PUT', url, params=None, data=None) |
| 88 | + |
| 89 | + def _detail(self, resource_ids, params=None, data=None): |
| 90 | + url = self.DETAIL_REQ_PATH % resource_ids |
| 91 | + return self.send_request('GET', url, params, data) |
| 92 | + |
| 93 | + |
| 94 | +class CollectionResponse(Model): |
| 95 | + items = [] |
| 96 | + success = BooleanType() |
| 97 | + |
| 98 | + def __init__(self, response, model_class): |
| 99 | + super(CollectionResponse, self).__init__() |
| 100 | + serialized = response.json() |
| 101 | + items = serialized['data'] or [] |
| 102 | + self.items = [dict_to_model(one, model_class) for one in items] |
| 103 | + |
| 104 | + |
| 105 | +def dict_to_model(data, model_class): |
| 106 | + """Converts the json response to a full fledge model |
| 107 | + The schematics model constructor is strict. If it sees keys that it |
| 108 | + doesn't know about it will raise an exception. This is a problem, both |
| 109 | + because we won't model all of the data at first, but also because the |
| 110 | + lib would break on new fields being returned. |
| 111 | + Therefore we inspect the model class and remove all keys not present |
| 112 | + before constructing the model. |
| 113 | + We also convert complex types to new models. |
| 114 | + Args: |
| 115 | + data(dict): The json response data as returned from the API. |
| 116 | + model_class(Model): The schematics model to instantiate |
| 117 | + Returns: |
| 118 | + Model: WIth the populated data |
| 119 | + """ |
| 120 | + data = deepcopy(data) |
| 121 | + model_keys = set(model_class.__dict__['_fields'].keys()) |
| 122 | + # This is a major clusterfuck. Pipedrive will return, for example |
| 123 | + # under the "user_id" key, the user dict. There fore we check if we |
| 124 | + # need to convert this |
| 125 | + for key in model_keys: |
| 126 | + if isinstance(model_class._fields[key], ModelType): |
| 127 | + response_key = key + "_id" |
| 128 | + if response_key in data: |
| 129 | + value = dict_to_model(data[response_key], |
| 130 | + getattr(model_class, key).model_class) |
| 131 | + del data[response_key] |
| 132 | + data[key] = value |
| 133 | + |
| 134 | + safe_keys = set(data.keys()).intersection(model_keys) |
| 135 | + safe_data = {key: data[key] for key in safe_keys} |
| 136 | + return model_class(raw_data=safe_data) |
| 137 | + |
| 138 | + |
| 139 | +class PipedriveDateTime(DateType): |
| 140 | + def to_native(self, value, context=None): |
| 141 | + return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S") |
0 commit comments