|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import requests |
| 4 | +from .version import API_VERSION, VERSION |
| 5 | +from . import models |
| 6 | +from .exceptions import ( |
| 7 | + APIError, |
| 8 | + ModelNotFoundError, |
| 9 | + InvalidCredentials, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +__title__ = 'atomx' |
| 14 | +__version__ = VERSION |
| 15 | +__author__ = 'Spot Media Solutions Sdn. Bhd.' |
| 16 | +__copyright__ = 'Copyright 2015 Spot Media Solutions Sdn. Bhd.' |
| 17 | + |
| 18 | + |
| 19 | +class Atomx(object): |
| 20 | + def __init__(self, email, password, api_endpoint='http://api.atomx.com/{}/'.format(API_VERSION)): |
| 21 | + self.email = email |
| 22 | + self.password = password |
| 23 | + self.api_endpoint = api_endpoint |
| 24 | + self.session = requests.Session() |
| 25 | + self.login() |
| 26 | + |
| 27 | + def login(self, email=None, password=None): |
| 28 | + if email: |
| 29 | + self.email = email |
| 30 | + if password: |
| 31 | + self.password = password |
| 32 | + |
| 33 | + r = self.session.post(self.api_endpoint + 'login', |
| 34 | + json={'email': self.email, 'password': self.password}) |
| 35 | + if not r.ok: |
| 36 | + if r.status_code == 401: |
| 37 | + raise InvalidCredentials |
| 38 | + raise APIError(r.json()['error']) |
| 39 | + self.auth_tk = r.json()['auth_tkt'] |
| 40 | + |
| 41 | + def logout(self): |
| 42 | + self.session.get(self.api_endpoint + 'logout') |
| 43 | + |
| 44 | + def search(self, query): |
| 45 | + r = self.session.get(self.api_endpoint + 'search', params={'q': query}) |
| 46 | + if not r.ok: |
| 47 | + raise APIError(r.json()['error']) |
| 48 | + return r.json()['search'] |
| 49 | + |
| 50 | + def get(self, model, **kwargs): |
| 51 | + if model not in dir(models): |
| 52 | + raise ModelNotFoundError() |
| 53 | + r = self.session.get(self.api_endpoint + model, params=kwargs) |
| 54 | + if not r.ok: |
| 55 | + raise APIError(r.json()['error']) |
| 56 | + |
| 57 | + r_json = r.json() |
| 58 | + model_name = model.lower() |
| 59 | + if model_name in r_json: |
| 60 | + return getattr(models, model)(self, **r_json[model_name]) |
| 61 | + return [getattr(models, model)(self, **m) for m in r_json[model_name + 's']] |
| 62 | + |
| 63 | + def post(self, model, json, **kwargs): |
| 64 | + return self.session.post(self.api_endpoint + model, json=json, params=kwargs) |
| 65 | + |
| 66 | + def put(self, model, id, json, **kwargs): |
| 67 | + return self.session.put(self.api_endpoint + model + '/' + str(id), json=json, params=kwargs) |
| 68 | + |
| 69 | + def delete(self, model, id, json, **kwargs): |
| 70 | + return self.session.put(self.api_endpoint + model + '/' + str(id), json=json, params=kwargs) |
0 commit comments