2
0

mailchimp.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from wagtail.models import Site
  2. from wagtailcrx.models.wagtailsettings_models import MailchimpApiSettings
  3. import requests
  4. class MailchimpApi:
  5. user_string = "Website"
  6. proto_base_url = "https://{0}.api.mailchimp.com/3.0/"
  7. def __init__(self, site=None):
  8. self.set_access_token(site=None)
  9. def set_access_token(self, site=None):
  10. site = site or Site.objects.get(is_default_site=True)
  11. self.access_token = MailchimpApiSettings.for_site(site).mailchimp_api_key
  12. if self.access_token:
  13. self.set_base_url()
  14. self.is_active = True
  15. else:
  16. self.is_active = False
  17. def set_base_url(self):
  18. """
  19. The base url for the mailchimip api is dependent on the api key.
  20. """
  21. key, datacenter = self.access_token.split('-')
  22. self.base_url = self.proto_base_url.format(datacenter)
  23. def default_headers(self):
  24. return {
  25. "Content-Type": "application/json",
  26. }
  27. def default_auth(self):
  28. return (self.user_string, self.access_token)
  29. def get_lists(self):
  30. endpoint = "lists?fields=lists.name,lists.id"
  31. json_response = self._get(endpoint)
  32. return json_response
  33. def get_merge_fields_for_list(self, list_id):
  34. endpoint = "lists/{0}/merge-fields?fields=merge_fields.tag,merge_fields.merge_id,merge_fields.name".format(list_id) # noqa
  35. json_response = self._get(endpoint)
  36. return json_response
  37. def get_interest_categories_for_list(self, list_id):
  38. endpoint = "lists/{0}/interest-categories?fields=categories.id,categories.title".format(
  39. list_id)
  40. json_response = self._get(endpoint)
  41. return json_response
  42. def get_interests_for_interest_category(self, list_id, interest_category_id):
  43. endpoint = "lists/{0}/interest-categories/{1}/interests?fields=interests.id,interests.name".format(list_id, interest_category_id) # noqa
  44. json_response = self._get(endpoint)
  45. return json_response
  46. def add_user_to_list(self, list_id, data):
  47. endpoint = "lists/{0}".format(list_id)
  48. json_response = self._post(endpoint, data=data)
  49. return json_response
  50. def _get(self, endpoint, data={}, auth=None, headers=None, **kwargs):
  51. auth = auth or self.default_auth()
  52. headers = headers or self.default_headers()
  53. full_url = "{0}{1}".format(self.base_url, endpoint)
  54. r = requests.get(full_url, auth=auth, headers=headers, data=data, **kwargs)
  55. return r.json()
  56. def _post(self, endpoint, data={}, auth=None, headers=None, **kwargs):
  57. auth = auth or self.default_auth()
  58. headers = headers or self.default_headers()
  59. full_url = "{0}{1}".format(self.base_url, endpoint)
  60. r = requests.post(full_url, auth=auth, headers=headers, data=data, **kwargs)
  61. return r.json()