Skip to content

Commit

Permalink
Merge pull request #2 from FullFact/1-mailchimp-marketing
Browse files Browse the repository at this point in the history
Switch to wrap mailchimp-marketing
  • Loading branch information
andylolz authored Jun 20, 2023
2 parents 7e50e1d + f5c81c1 commit b26344f
Show file tree
Hide file tree
Showing 5 changed files with 324 additions and 128 deletions.
29 changes: 14 additions & 15 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ Python BatchMailchimp
:alt: License
:target: https://pypi.org/project/batch-mailchimp/

A light wrapper around `mailchimp3 <https://pypi.org/project/mailchimp3/>`__ that makes it easier to use batch
operations.
A light wrapper around `mailchimp-marketing <https://pypi.org/project/mailchimp-marketing/>`__ that makes it easier to use batch operations.

Getting Started
---------------
Expand All @@ -25,34 +24,34 @@ Installation
Usage
~~~~~

This can be used as a drop-in replacement for mailchimp3 – just change
the import at the top, and everything should work the same:
This can be used as a drop-in replacement for mailchimp-marketing –
just change the import at the top, and everything should work the same:

.. code:: python
from batch_mailchimp import BatchMailChimp as MailChimp
import batch_mailchimp as MailchimpMarketing
client = MailChimp(
mc_api='YOUR_API_KEY',
mc_user='YOUR_USERNAME')
client = MailchimpMarketing.Client({
"api_key": "YOUR_API_KEY",
})
The additional functionality comes when we initialise the client with ``batch=True``:

.. code:: python
from batch_mailchimp import BatchMailChimp as MailChimp
import batch_mailchimp as MailchimpMarketing
batch_client = MailChimp(
mc_api='YOUR_API_KEY',
mc_user='YOUR_USERNAME',
batch=True)
client = MailchimpMarketing.Client({
"api_key": "YOUR_API_KEY",
"batch": True,
})
If we do this, operations are stored up in the client, to be run later. For example:

.. code:: python
# add John Doe with email john.doe@example.com to list matching id '123456'
batch_client.lists.members.create(
client.lists.members.create(
'123456', {
'email_address': 'john.doe@example.com',
'status': 'subscribed',
Expand All @@ -67,7 +66,7 @@ All new operations will be added to the batch. When we’re ready, we can run al

.. code:: python
batch = batch_client.batch.run()
batch = batch_client.batches.run()
We can check the batch’s status using:

Expand Down
188 changes: 112 additions & 76 deletions batch_mailchimp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,122 @@
import json
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse

from mailchimp3 import MailChimp

from .batch_operations import BatchOperations


class Batch:
def __init__(self, client):
self._mc_client = client
self.operations = []
self._run = False
self.id = None

def __getitem__(self, item):
if item == 'id':
return self.id

def __repr__(self):
return '<{}.{}: {} operation{}{}>'.format(
self.__class__.__module__,
self.__class__.__name__,
len(self.operations),
's' if len(self.operations) != 1 else '',
'*' if not self._run else '',
)

def _pause_batch(fn):
def wrapper(self, *args, **kwargs):
self._mc_client._is_paused = True
resp = fn(self, *args, **kwargs)
self._mc_client._is_paused = False
return resp
return wrapper

@_pause_batch
def status(self, **kwargs):
return self._mc_client.batch_operations.get(self, **kwargs)

@_pause_batch
def run(self):
self._mc_client.batch_operations.create(self)
self._mc_client.batch = None
return self

@_pause_batch
def delete(self):
return self._mc_client.batch_operations.delete(self)
import uuid
from six.moves.urllib.parse import urlparse
from mailchimp_marketing.api.surveys_api import SurveysApi
from mailchimp_marketing.api.account_export_api import AccountExportApi
from mailchimp_marketing.api.account_exports_api import AccountExportsApi
from mailchimp_marketing.api.activity_feed_api import ActivityFeedApi
from mailchimp_marketing.api.authorized_apps_api import AuthorizedAppsApi
from mailchimp_marketing.api.automations_api import AutomationsApi
from mailchimp_marketing.api.batch_webhooks_api import BatchWebhooksApi
from mailchimp_marketing.api.campaign_folders_api import CampaignFoldersApi
from mailchimp_marketing.api.campaigns_api import CampaignsApi
from mailchimp_marketing.api.connected_sites_api import ConnectedSitesApi
from mailchimp_marketing.api.conversations_api import ConversationsApi
from mailchimp_marketing.api.customer_journeys_api import CustomerJourneysApi
from mailchimp_marketing.api.ecommerce_api import EcommerceApi
from mailchimp_marketing.api.facebook_ads_api import FacebookAdsApi
from mailchimp_marketing.api.file_manager_api import FileManagerApi
from mailchimp_marketing.api.landing_pages_api import LandingPagesApi
from mailchimp_marketing.api.lists_api import ListsApi
from mailchimp_marketing.api.ping_api import PingApi
from mailchimp_marketing.api.reporting_api import ReportingApi
from mailchimp_marketing.api.reports_api import ReportsApi
from mailchimp_marketing.api.root_api import RootApi
from mailchimp_marketing.api.search_campaigns_api import SearchCampaignsApi
from mailchimp_marketing.api.search_members_api import SearchMembersApi
from mailchimp_marketing.api.template_folders_api import TemplateFoldersApi
from mailchimp_marketing.api.templates_api import TemplatesApi
from mailchimp_marketing.api.verified_domains_api import VerifiedDomainsApi
from mailchimp_marketing import api_client
from mailchimp_marketing import Client as MailChimpClient

from .batches_api import BatchesApi


class FakeRequest:
def __init__(self, batch, **kwargs):
self.status_code = 200
self.batch = batch
path = urlparse(kwargs.get('url')).path[4:]
operation = {
'method': kwargs.get('method'),
'path': path,
def __init__(self, operation_id):
self.ok = True
self.headers = {
"content-type": "application/json"
}
if 'json' in kwargs:
operation['body'] = json.dumps(kwargs['json'])
self.batch.operations.append(operation)
self._operation_id = operation_id

def json(self):
return self.batch
return {
"okay": True,
"operation_id": self._operation_id,
}


class BatchMailChimp(MailChimp):
def __init__(self, *args, batch=False, **kwargs):
super(BatchMailChimp, self).__init__(*args, **kwargs)
self._is_batch = batch
self._is_paused = False
self.batch = None
# Batch Operations
self.batches = self.batch_operations = BatchOperations(self)
class ApiClient(api_client.ApiClient):
def __init__(self, config={}):
self.operations = []
self.set_batch_mode(config.get("batch", False))
super().__init__(config)

def set_batch_mode(self, state):
self.batch_mode = state

def set_config(self, config={}):
if "batch" in config:
if self.operations and not config["batch"]:
raise Exception("Can’t disable batch mode")
self.batch_mode = config["batch"]
super().set_config(config)

def request(self, method, url, query_params=None, headers=None, body=None):
if not self.batch_mode:
return super().request(method, url, query_params, headers, body)
operation = {
"method": method,
"path": urlparse(url).path[4:],
"operation_id": uuid.uuid4().hex,
}
if query_params:
operation["params"] = query_params
if body:
operation["body"] = json.dumps(body)

self.operations.append(operation)
return FakeRequest(operation["operation_id"])


class Client(MailChimpClient):
def __init__(self, config={}):
self.api_client = ApiClient(config)

self.Surveys = SurveysApi(self.api_client)
self.accountExport = AccountExportApi(self.api_client)
self.accountExports = AccountExportsApi(self.api_client)
self.activityFeed = ActivityFeedApi(self.api_client)
self.authorizedApps = AuthorizedAppsApi(self.api_client)
self.automations = AutomationsApi(self.api_client)
self.batchWebhooks = BatchWebhooksApi(self.api_client)
self.batches = BatchesApi(self.api_client)
self.campaignFolders = CampaignFoldersApi(self.api_client)
self.campaigns = CampaignsApi(self.api_client)
self.connectedSites = ConnectedSitesApi(self.api_client)
self.conversations = ConversationsApi(self.api_client)
self.customerJourneys = CustomerJourneysApi(self.api_client)
self.ecommerce = EcommerceApi(self.api_client)
self.facebookAds = FacebookAdsApi(self.api_client)
self.fileManager = FileManagerApi(self.api_client)
self.landingPages = LandingPagesApi(self.api_client)
self.lists = ListsApi(self.api_client)
self.ping = PingApi(self.api_client)
self.reporting = ReportingApi(self.api_client)
self.reports = ReportsApi(self.api_client)
self.root = RootApi(self.api_client)
self.searchCampaigns = SearchCampaignsApi(self.api_client)
self.searchMembers = SearchMembersApi(self.api_client)
self.templateFolders = TemplateFoldersApi(self.api_client)
self.templates = TemplatesApi(self.api_client)
self.verifiedDomains = VerifiedDomainsApi(self.api_client)
self.batches = BatchesApi(self.api_client)

def _make_request(self, **kwargs):
if self._is_batch and not self._is_paused:
if not self.batch:
self.batch = Batch(self)
return FakeRequest(self.batch, **kwargs)
return super(BatchMailChimp, self)._make_request(**kwargs)
def __repr__(self):
return "<{module}.{name}: batch mode {batch_mode_toggle}>".format(
module=self.__class__.__module__,
name=self.__class__.__name__,
batch_mode_toggle="ON" if self.api_client.batch_mode else "OFF",
)
35 changes: 0 additions & 35 deletions batch_mailchimp/batch_operations.py

This file was deleted.

Loading

0 comments on commit b26344f

Please sign in to comment.