Advertisement
Guest User

Untitled

a guest
Jan 11th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. #!/usr/bin/python
  2. # coding=utf-8
  3. import requests
  4. import json
  5.  
  6.  
  7. class DeskError(Exception):
  8.  
  9.     def __init__(self, status):
  10.         Exception.__init__(self, status)  # Exception is an old-school class
  11.         self.status = status
  12.  
  13.     def __str__(self):
  14.         return self.status
  15.  
  16.     def __unicode__(self):
  17.         return unicode(self.__str__())
  18.  
  19.  
  20. class DeskClient(object):
  21.     BASE_URL = 'desk.com/api/v2'
  22.     sitename = "värde"
  23.     username = "värde"
  24.     password = "värde"
  25.  
  26.     def __init__(self, sitename, username, password):
  27.         self.sitename = sitename
  28.         self.username = username
  29.         self.password = password
  30.  
  31.     def build_url(self, service):
  32.         return 'https://%s.%s/%s' % (self.sitename,
  33.                                      DeskClient.BASE_URL, service)
  34.  
  35.     def call_get(self, service, params=None):
  36.         url = self.build_url(service)
  37.         r = requests.get(url, params=params,
  38.                          auth=(self.username, self.password))
  39.         print r.content
  40.         if r.status_code != requests.codes.ok:
  41.             raise DeskError(str(r.status_code))
  42.         return json.loads(r.content)
  43.  
  44.     def call_post(self, service, data=None):
  45.         url = self.build_url(service)
  46.         r = requests.post(url, data=json.dumps(data),
  47.                           auth=(self.username, self.password))
  48.         if r.status_code >= 400:
  49.             raise DeskError(str(r.status_code))
  50.         return json.loads(r.content)
  51.  
  52.     def find_customer(self, params):
  53.         customer_link = None
  54.         try:
  55.             customer_json = self.call_get('customers/search', params)
  56.             if customer_json['total_entries'] > 0:
  57.                 customer_link = customer_json['_embedded'][
  58.                     'entries'][0]['_links']['self']
  59.         except DeskError:
  60.             pass
  61.         return customer_link
  62.  
  63.     if __name__ == "__main__":
  64.         search_name = raw_input("Search for customer: ")
  65.         find_customer(search_name)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement