Repository: VingtCinq/python-mailchimp Branch: master Commit: bf61cd602dc4 Files: 86 Total size: 317.3 KB Directory structure: gitextract_mzccawi9/ ├── .gitignore ├── LICENSE ├── README.md ├── README.rst ├── mailchimp3/ │ ├── __init__.py │ ├── baseapi.py │ ├── entities/ │ │ ├── __init__.py │ │ ├── authorizedapps.py │ │ ├── automationactions.py │ │ ├── automationemailactions.py │ │ ├── automationemailqueues.py │ │ ├── automationemails.py │ │ ├── automationremovedsubscribers.py │ │ ├── automations.py │ │ ├── batchoperations.py │ │ ├── batchwebhooks.py │ │ ├── campaignactions.py │ │ ├── campaigncontent.py │ │ ├── campaignfeedback.py │ │ ├── campaignfolders.py │ │ ├── campaigns.py │ │ ├── campaignsendchecklist.py │ │ ├── conversationmessages.py │ │ ├── conversations.py │ │ ├── customerjourney.py │ │ ├── filemanagerfiles.py │ │ ├── filemanagerfolders.py │ │ ├── landingpageaction.py │ │ ├── landingpagecontent.py │ │ ├── landingpages.py │ │ ├── listabusereports.py │ │ ├── listactivity.py │ │ ├── listclients.py │ │ ├── listgrowthhistory.py │ │ ├── listinterestcategories.py │ │ ├── listinterestcategoryinterest.py │ │ ├── listmemberactivity.py │ │ ├── listmemberevents.py │ │ ├── listmembergoals.py │ │ ├── listmembernotes.py │ │ ├── listmembers.py │ │ ├── listmembertags.py │ │ ├── listmergefields.py │ │ ├── lists.py │ │ ├── listsegmentmembers.py │ │ ├── listsegments.py │ │ ├── listsignupforms.py │ │ ├── listwebhooks.py │ │ ├── ping.py │ │ ├── reportcampaignabusereports.py │ │ ├── reportcampaignadvice.py │ │ ├── reportclickdetailmembers.py │ │ ├── reportclickdetailreports.py │ │ ├── reportdomainperformance.py │ │ ├── reporteepurl.py │ │ ├── reportemailactivity.py │ │ ├── reportgoogleanalytics.py │ │ ├── reportlocations.py │ │ ├── reportopendetails.py │ │ ├── reports.py │ │ ├── reportsentto.py │ │ ├── reportsubreports.py │ │ ├── reportunsubscribes.py │ │ ├── root.py │ │ ├── searchcampaigns.py │ │ ├── searchmembers.py │ │ ├── segments.py │ │ ├── storecartlines.py │ │ ├── storecarts.py │ │ ├── storecustomers.py │ │ ├── storeorderlines.py │ │ ├── storeorders.py │ │ ├── storeproductimages.py │ │ ├── storeproducts.py │ │ ├── storeproductvariants.py │ │ ├── storepromocodes.py │ │ ├── storepromorules.py │ │ ├── stores.py │ │ ├── templatedefaultcontent.py │ │ ├── templatefolders.py │ │ └── templates.py │ ├── helpers.py │ └── mailchimpclient.py ├── setup.cfg ├── setup.py └── test.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ venv/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # PyCharm project files .idea # vscode .vscode # sonarlint .sonarlint ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Charles TISSIER Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ [![mailchimp3 v3.0.21 on PyPi](https://img.shields.io/pypi/v/mailchimp3.svg)](https://pypi.python.org/pypi/mailchimp3) ![MIT license](https://img.shields.io/badge/licence-MIT-blue.svg) ![Stable](https://img.shields.io/badge/status-stable-green.svg) # python-mailchimp-api A straightforward python client for v3 of MailChimp API using requests >= 2.7.0. ## Getting Started ### Installation This client is hosted at PyPi under the name `mailchimp3`, to install it, simply run `pip install mailchimp3` ### Upgrading from v2.x The order of arguments for initializing the Mailchimp API has been reversed starting in 2.1.0 as the username is an optional argument for basic auth. Please reverse the order of your arguments or remove the username argument entirely. The name of the authentication argument has also changed from `mc_secret` to `mc_api`. ### Upgrading from v1.x The installation procedure for 2.x is the same as before, however there are a massive number of changes to the naming conventions within this wrapper and the way in which certain methods are called. Please read the documentation below carefully for information on the new structure and expanded functionality. With this release, all documented endpoints are implemented and all endpoint methods are available. ### History Up to date with [changelog](http://developer.mailchimp.com/documentation/mailchimp/guides/changelog/) features listed through 3/03/2017. ### Initialization Grab `YOUR_API_KEY` from your mailchimp account (Account > Extra > Api Keys). `YOUR_USERNAME` is the one you use to log in on the website and is optional. from mailchimp3 import MailChimp client = MailChimp(mc_api='YOUR_API_KEY', mc_user='YOUR_USERNAME') ### OAuth Support In addition to HTTP Basic Authentication, MailChimp supports authentication through OAuth2. Information on obtaining the proper access key can be found [here](http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-oauth2/). ### Pagination Simply add `count` and `offset` arguments in your function. The count is how many records to return, the offset is how many records to skip. For endpoints that allow the pagination parameters, the all() method has an additional boolean `get_all` argument that will loop through all records until the API no longer returns any to get all records without manually performing an additional query. By default, count is 10 and offset is 0 for all endpoints that support it. The `get_all` parameter on the all() method on any endpoint defaults to false, which follows the values that are provided in the call, and using `get_all=True` will ignore the provided offset to ensure that all records are returned. When using get_all, the count will be 500 unless otherwise specified. It is strongly recommended to avoid small values for `count` to fetch large numbers of records because this will flood the system. A large `count` size should not impact calls which are expected to return a very small number of records, and should improve performance for calls where fetching 500 records would only provide a fraction by preventing the delay of making a huge number of requests. client.lists.members.all('123456', count=100, offset=0) ### Fields Many endpoints allow you to select which fields will be returned out of all available fields (for example, only the email_address of a member). Simply add `fields` arguments in your function. The following only display email_address and id for each member in list 123456: client.lists.members.all('123456', get_all=True, fields="members.email_address,members.id") ### Examples # returns all the lists (only name and id) client.lists.all(get_all=True, fields="lists.name,lists.id") # returns all members inside list '123456' client.lists.members.all('123456', get_all=True) # return the first 100 member's email addresses for the list with id 123456 client.lists.members.all('123456', count=100, offset=0, fields="members.email_address") # returns the list matching id '123456' client.lists.get('123456') # add John Doe with email john.doe@example.com to list matching id '123456' client.lists.members.create('123456', { 'email_address': 'john.doe@example.com', 'status': 'subscribed', 'merge_fields': { 'FNAME': 'John', 'LNAME': 'Doe', }, }) # returns all the campaigns client.campaigns.all(get_all=True) # You can also disable at runtime with the optional ``enabled`` parameter. # Every API call will return None client = MailChimp('YOUR SECRET KEY', enabled=False) # You are encouraged to specify a value in seconds for the ``timeout`` # parameter to avoid hanging requests. client = MailChimp('YOUR SECRET KEY', timeout=10.0) # You are encouraged to specify a User-Agent for requests to the MailChimp # API. Headers can be specified using the ``request_headers`` parameter. headers = requests.utils.default_headers() headers['User-Agent'] = 'Example (example@example.com)' client = MailChimp('YOUR SECRET KEY', request_headers=headers) ## API Structure All endpoints follow the structure listed in the official MailChimp API v3 documentation. The structure will be listed below and then the individual methods available after. MailChimp +- Root +- Authorized Apps +- Automations | +- Actions | +- Emails | | +- Actions | | +- Queues | +- Removed Subscribers +- Batch Operations +- Batch Webhooks +- Campaign Folders +- Campaigns | +- Actions | +- Content | +- Feedback | +- Send Checklist +- Conversations | +- Messages +- Customer Journeys +- Stores | +- Carts | | +- Lines | +- Customers | +- Orders | | +- Lines | +- Products | +- Images | +- Variants | +- Promo Rules | +- Promo Codes +- File Manager Files +- File Manager Folders +- Landing Pages | +- Actions | +- Content +- Lists | +- Abuse Reports | +- Activity | +- Clients | +- Growth History | +- Interest Categories | | +- Interests | +- Members | | +- Activity | | +- Events | | +- Goals | | +- Notes | | +- Tags | +- Merge Fields | +- Segments | | +- Segment Members | +- Signup Forms | +- Twitter Lead Generation Carts | +- Webhooks +- Ping +- Reports | +- Campaign Abuse | +- Campaign Advice | +- Campaign Open reports | +- Click Reports | | +- Members | +- Domain Performance | +- EepURL Reports | +- Email Activity | +- Google Analytics | +- Location | +- Sent To | +- Sub-Reports | +- Unsubscribes +- Search Campaigns +- Search Members +- Template Folders +- Templates +- Default Content ## API Endpoints Below is the list of all endpoints and the methods that can be called against them. Any endpoint that has a method that takes an ID argument (for example the app_id in the authorized_apps endpoint or the subscriber_hash in the list members endpoints) will record all IDs passed as well as those generated by methods that will only ever return a single result such as the create() method present on some endpoints. These stored attributes are only available at the level that they were passed or created at and must be passed again to interact with a lower or higher level such as accessing a list and then a member. The below code assumes that you have initialized the MailChimp class as listed above with the name `client`. ### Root #### Root client.root.get() ### Authorized Apps #### Authorized Apps client.authorized_apps.create(data={}) client.authorized_apps.all(get_all=False) client.authorized_apps.get(app_id='') ### Automations #### Automations client.automations.all(get_all=False) client.automations.get(workflow_id='') #### Automation Actions client.automations.actions.pause(workflow_id='') client.automations.actions.start(workflow_id='') #### Automation Emails client.automations.emails.all(workflow_id='') client.automations.emails.get(workflow_id='', email_id='') #### Automation Email Actions client.automations.emails.actions.pause(workflow_id='', email_id='') client.automations.emails.actions.start(workflow_id='', email_id='') #### Automation Email Queues client.automations.emails.queues.create(workflow_id='', email_id='', data={}) client.automations.emails.queues.all(workflow_id='', email_id='') client.automations.emails.queues.get(workflow_id='', email_id='', subscriber_hash='') #### Automation Removed Subscribers client.automations.removed_subscribers.create(workflow_id='', data={}) client.automations.removed_subscribers.all(workflow_id='') ### Batch Operations #### Batch Operations client.batch_operations.create(data={}) client.batch_operations.all(get_all=False) client.batch_operations.get(batch_id='') client.batch_operations.delete(batch_id='') ### Batch Webhooks #### Batch Webhooks client.batch_webhooks.create(data={}) client.batch_webhooks.all(get_all=False) client.batch_webhooks.get(batch_webhook_id='') client.batch_webhooks.update(batch_webhook_id='', data={}) client.batch_webhooks.delete(batch_webhook_id='') ### Campaigns #### Folders client.campaign_folders.create(data={}) client.campaign_folders.all(get_all=False) client.campaign_folders.get(folder_id='') client.campaign_folders.update(folder_id='', data={}) client.campaign_folders.delete(folder_id='') #### Campaigns client.campaigns.create(data={}) client.campaigns.all(get_all=False) client.campaigns.get(campaign_id='') client.campaigns.update(campaign_id='') client.campaigns.delete(campaign_id='') #### Campaign Actions client.campaigns.actions.cancel(campaign_id='') client.campaigns.actions.pause(campaign_id='') client.campaigns.actions.replicate(campaign_id='') client.campaigns.actions.resume(campaign_id='') client.campaigns.actions.schedule(campaign_id='', data={}) client.campaigns.actions.send(campaign_id='') client.campaigns.actions.resend(campaign_id='') client.campaigns.actions.test(campaign_id='', data={}) client.campaigns.actions.unschedule(campaign_id='') #### Campaign Content client.campaigns.content.get(campaign_id='') client.campaigns.content.update(campaign_id='', data={}) #### Campaign Feedback client.campaigns.feedback.create(campaign_id='', data={}) client.campaigns.feedback.all(campaign_id='', get_all=False) client.campaigns.feedback.get(campaign_id='', feedback_id='') client.campaigns.feedback.update(campaign_id='', feedback_id='', data={}) client.campaigns.feedback.delete(campaign_id='', feedback_id='') #### Campaign Send Checklist client.campaigns.send_checklist.get(campaign_id='') ### Conversations #### Conversations client.conversations.all(get_all=False) client.conversations.get(conversation_id='') #### Conversation Messages client.conversations.messages.create(conversation_id='', data={}) client.conversations.messages.all(conversation_id='') client.conversations.messages.get(conversation_id='', message_id='') ### Customer Journeys #### Customer Journeys client.customer_journeys.trigger(journey_id='', step_id='', data={}) ### E-Commerce #### Stores client.stores.create(data={}) client.stores.all(get_all=False) client.stores.get(store_id='') client.stores.update(store_id='', data={}) client.stores.delete(store_id='') #### Store Carts client.stores.carts.create(store_id='', data={}) client.stores.carts.all(store_id='', get_all=False) client.stores.carts.get(store_id='', cart_id='') client.stores.carts.update(store_id='', cart_id='', data={}) client.stores.carts.delete(store_id='', cart_id='') #### Store Cart Lines client.stores.carts.lines.create(store_id='', cart_id='', data={}) client.stores.carts.lines.all(store_id='', cart_id='', get_all=False) client.stores.carts.lines.get(store_id='', cart_id='', line_id='') client.stores.carts.lines.update(store_id='', cart_id='', line_id='', data={}) client.stores.carts.lines.delete(store_id='', cart_id='', line_id='') #### Store Customers client.stores.customers.create(store_id='', data={}) client.stores.customers.all(store_id='', get_all=False) client.stores.customers.get(store_id='', customer_id='') client.stores.customers.update(store_id='', customer_id='', data={}) client.stores.customers.create_or_update(store_id='', customer_id='', data={}) client.stores.customers.delete(store_id='', customer_id='') #### Store Orders client.stores.orders.create(store_id='', data={}) client.stores.orders.all(store_id='', get_all=False) client.stores.orders.get(store_id='', order_id='') client.stores.orders.update(store_id='', order_id='', data={}) client.stores.orders.delete(store_id='', order_id='') #### Store Order Lines client.stores.orders.lines.create(store_id='', order_id='', data={}) client.stores.orders.lines.all(store_id='', order_id='', get_all=False) client.stores.orders.lines.get(store_id='', order_id='', line_id='') client.stores.orders.lines.update(store_id='', order_id='', line_id='', data={}) client.stores.orders.lines.delete(store_id='', order_id='', line_id='') #### Store Products client.stores.products.create(store_id='', data={}) client.stores.products.all(store_id='', get_all=False) client.stores.products.get(store_id='', product_id='') client.stores.products.update(store_id='', product_id='') client.stores.products.delete(store_id='', product_id='') #### Store Product Images client.stores.products.images.create(store_id='', product_id='', data={}) client.stores.products.images.all(store_id='', product_id='', get_all=False) client.stores.products.images.get(store_id='', product_id='', image_id='') client.stores.products.images.update(store_id='', product_id='', image_id='', data={}) client.stores.products.images.delete(store_id='', product_id='', image_id='') #### Store Product Variants client.stores.products.variants.create(store_id='', product_id='', data={}) client.stores.products.variants.all(store_id='', product_id='', get_all=False) client.stores.products.variants.get(store_id='', product_id='', variant_id='') client.stores.products.variants.update(store_id='', product_id='', variant_id='', data={}) client.stores.products.variants.create_or_update(store_id='', product_id='', variant_id='', data={}) client.stores.products.variants.delete(store_id='', product_id='', variant_id='') ### File Manager #### Files client.files.create(data={}) client.files.all(get_all=False) client.files.get(file_id='') client.files.update(file_id='', data={}) client.files.delete(file_id='') #### Folders client.folders.create(data={}) client.folders.all(get_all=False) client.folders.get(folder_id='') client.folders.update(folder_id='', data={}) client.folders.delete(folder_id='') ### Landing Pages #### Landing Pages client.landing_pages.create(data={}) client.landing_pages.all() client.landing_pages.all(fields='') client.landing_pages.get(page_id='') client.landing_pages.update(page_id='', data={}) client.landing_pages.delete(page_id='') #### Landing Pages Actions client.landing_pages.actions.publish(page_id='') client.landing_pages.actions.unpublish(page_id='') #### Landing Pages Content client.landing_pages.content.get(page_id='') ### Lists #### Lists client.lists.create(data={}) client.lists.update_members(list_id='', data={}) client.lists.all(get_all=False) client.lists.get(list_id='') client.lists.update(list_id='', data={}) client.lists.delete(list_id='') #### List Abuse Reports client.lists.abuse_reports.all(list_id='', get_all=False) client.lists.abuse_reports.get(list_id='', report_id='') #### List Activity client.lists.activity.all(list_id='', subscriber_hash='') client.lists.activity.feed(list_id='', subscriber_hash='') #### List Clients client.lists.clients.all(list_id='') #### List Growth History client.lists.growth_history.all(list_id='', get_all=False) client.lists.growth_history.get(list_id='', month='') #### List Interest Categories client.lists.interest_categories.create(list_id='', data={}) client.lists.interest_categories.all(list_id='', get_all=False) client.lists.interest_categories.get(list_id='', category_id='') client.lists.interest_categories.update(list_id='', category_id='', data={}) client.lists.interest_categories.delete(list_id='', category_id='') #### List Interest Category Interests client.lists.interest_categories.interests.create(list_id='', category_id='', data={}) client.lists.interest_categories.interests.all(list_id='', category_id='', get_all=False) client.lists.interest_categories.interests.get(list_id='', category_id='', interest_id='') client.lists.interest_categories.interests.update(list_id='', category_id='', interest_id='', data={}) client.lists.interest_categories.interests.delete(list_id='', category_id='', interest_id='') #### List Members client.lists.members.create(list_id='', data={}) client.lists.members.all(list_id='', get_all=False) client.lists.members.get(list_id='', subscriber_hash='') client.lists.members.update(list_id='', subscriber_hash='', data={}) client.lists.members.create_or_update(list_id='', subscriber_hash='', data={}) client.lists.members.delete(list_id='', subscriber_hash='') client.lists.members.delete_permanent(list_id='', subscriber_hash='') #### List Member Activity client.lists.members.activity.all(list_id='', subscriber_hash='') #### List Member Events client.lists.members.events.create(list_id='', subscriber_hash='', data={}) client.lists.members.events.all(list_id='', subscriber_hash='', get_all=False) #### List Member Goals client.lists.members.goals.all(list_id='', subscriber_hash='') #### List Member Notes client.lists.members.notes.create(list_id='', subscriber_hash='', data={}) client.lists.members.notes.all(list_id='', subscriber_hash='', get_all=False) client.lists.members.notes.get(list_id='', subscriber_hash='', note_id='') client.lists.members.notes.update(list_id='', subscriber_hash='', note_id='', data={}) client.lists.members.notes.delete(list_id='', subscriber_hash='', note_id='') #### List Member Tags client.lists.members.tags.update(list_id='', subscriber_hash='', data={}) client.lists.members.tags.all(list_id='', subscriber_hash='') #### List Merge Fields client.lists.merge_fields.create(list_id='', data={}) client.lists.merge_fields.all(list_id='', get_all=False) client.lists.merge_fields.get(list_id='', merge_id='') client.lists.merge_fields.update(list_id='', merge_id='', data={}) client.lists.merge_fields.delete(list_id='', merge_id='') #### List Segments client.lists.segments.create(list_id='', data={}) client.lists.segments.all(list_id='', get_all=False) client.lists.segments.get(list_id='', segment_id='') client.lists.segments.update(list_id='', segment_id='', data={}) client.lists.segments.update_members(list_id='', segment_id='', data={}) client.lists.segments.delete(list_id='', segment_id='') #### List Segment Members client.lists.segments.members.create(list_id='', segment_id='', data={}) client.lists.segments.members.all(list_id='', segment_id='', get_all=False) client.lists.segments.members.delete(list_id='', segment_id='', subscriber_hash='') #### List Signup Forms client.lists.signup_forms.create(list_id='', data={}) client.lists.signup_forms.all(list_id='') #### List Webhooks client.lists.webhooks.create(list_id='', data={}) client.lists.webhooks.all(list_id='') client.lists.webhooks.get(list_id='', webhook_id='') client.lists.webhooks.update(list_id='', webhook_id='', data={}) client.lists.webhooks.delete(list_id='', webhook_id='') ### Reports #### Reports client.reports.all(get_all=False) client.reports.get(campaign_id='') #### Campaign Abuse Reports client.reports.abuse_reports.all(campaign_id='') client.reports.abuse_reports.get(campaign_id='', report_id='') #### Campaign Advice client.reports.advice.all(campaign_id='') #### Click Details Report client.reports.click_details.all(campaign_id='', get_all=False) client.reports.click_details.get(campaign_id='', link_id='') #### Click Details Report Members client.reports.click_details.members.all(campaign_id='', link_id='', get_all=False) client.reports.click_details.members.get(campaign_id='', link_id='', subscriber_hash='') #### Domain Performance Reports client.reports.domain_performance.all(campaign_id='') #### EepURL Reports client.reports.eepurl.all(camnpaign_id='') #### Email Activity Reports client.reports.email_activity.all(campaign_id='', get_all=False) client.reports.email_activity.get(campaign_id='', subscriber_hash='') #### Locations Report client.reports.locations.all(campaign_id='', get_all=False) #### Sent To Reports client.reports.sent_to.all(campaign_id='', get_all=False) client.reports.sent_to.get(campaign_id='', subscriber_hash='') #### Sub-Reports client.reports.subreports.all(campaign_id='') #### Unsubscribes client.reports.unsubscribes.all(campaign_id='', get_all=False) client.reports.unsubscribes.get(campaign_id='', subscriber_hash='') ### Search #### Campaigns client.search_campaigns.get() #### Members client.search_members.get() ### Templates #### Folders client.template_folders.create(data={}) client.template_folders.all(get_all=False) client.template_folders.get(folder_id='') client.template_folders.update(folder_id='', data={}) client.template_folders.delete(folder_id='') #### Templates client.templates.create(data={}) client.templates.all(get_all=False) client.templates.get(template_id='') client.templates.update(template_id='', data={}) client.templates.delete(template_id='') #### Default Content client.templates.default_content.all(template_id='') ## Logging The MailChimp client will log request/response detail into the mailchimp3.client logging namespace. Consider the following snippet to get started with logging: ```python import logging fh = logging.FileHandler('/path/to/some/log.log') logger = logging.getLogger('mailchimp3.client') logger.addHandler(fh) # use the client normally client.lists.all(**{'fields': 'lists.date_created'}) ``` request/response detail will be appended into /path/to/some/log.log: ``` GET Request: https://us15.api.mailchimp.com/3.0/lists?fields=lists.date_created GET Response: 200 {"lists":[{"date_created":"2017-05-10T13:53:05+00:00"},{"date_created":"2017-08-22T20:27:56+00:00"},{"date_created":"2017-05-12T21:22:15+00:00"},{"date_created":"2017-04-27T17:42:04+00:00"},{"date_created":"2017-05-10T14:14:49+00:00"},{"date_created":"2017-05-10T13:52:37+00:00"},{"date_created":"2017-05-10T13:51:40+00:00"}]} ``` Check the [docs](https://docs.python.org/2/library/logging.html) for more detail on the Python logging package. ## Support If you are having issues, please let us know or submit a pull request. ## License The project is licensed under the MIT License. ================================================ FILE: README.rst ================================================ |mailchimp3 v3.0.21 on PyPi| |MIT license| |Stable| python-mailchimp-api ==================== A straightforward python client for v3 of MailChimp API using requests >= 2.7.0. Getting Started --------------- Installation ~~~~~~~~~~~~ This client is hosted at PyPi under the name ``mailchimp3``, to install it, simply run ``pip install mailchimp3`` Upgrading from v2.x ~~~~~~~~~~~~~~~~~~~ The order of arguments for initializing the Mailchimp API has been reversed starting in 2.1.0 as the username is an optional argument for basic auth. Please reverse the order of your arguments or remove the username argument entirely. The name of the authentication argument has also changed from ``mc_secret`` to ``mc_api``. Upgrading from v1.x ~~~~~~~~~~~~~~~~~~~ The installation procedure for 2.x is the same as before, however there are a massive number of changes to the naming conventions within this wrapper and the way in which certain methods are called. Please read the documentation below carefully for information on the new structure and expanded functionality. With this release, all documented endpoints are implemented and all endpoint methods are available. History ~~~~~~~ Up to date with `changelog `__ features listed through 3/03/2017. Initialization ~~~~~~~~~~~~~~ Grab ``YOUR_API_KEY`` from your mailchimp account (Account > Extra > Api Keys). ``YOUR_USERNAME`` is the one you use to log in on the website and is optional. :: from mailchimp3 import MailChimp client = MailChimp(mc_api='YOUR_API_KEY', mc_user='YOUR_USERNAME') OAuth Support ~~~~~~~~~~~~~ In addition to HTTP Basic Authentication, MailChimp supports authentication through OAuth2. Information on obtaining the proper access key can be found `here `__. Pagination ~~~~~~~~~~ Simply add ``count`` and ``offset`` arguments in your function. The count is how many records to return, the offset is how many records to skip. For endpoints that allow the pagination parameters, the all() method has an additional boolean ``get_all`` argument that will loop through all records until the API no longer returns any to get all records without manually performing an additional query. By default, count is 10 and offset is 0 for all endpoints that support it. The ``get_all`` parameter on the all() method on any endpoint defaults to false, which follows the values that are provided in the call, and using ``get_all=True`` will ignore the provided offset to ensure that all records are returned. When using get_all, the count will be 500 unless otherwise specified. It is strongly recommended to avoid small values for ``count`` to fetch large numbers of records because this will flood the system. A large ``count`` size should not impact calls which are expected to return a very small number of records, and should improve performance for calls where fetching 500 records would only provide a fraction by preventing the delay of making a huge number of requests. :: client.lists.members.all('123456', count=100, offset=0) Fields ~~~~~~ Many endpoints allow you to select which fields will be returned out of all available fields (for example, only the email_address of a member). Simply add ``fields`` arguments in your function. The following only display email_address and id for each member in list 123456: :: client.lists.members.all('123456', get_all=True, fields="members.email_address,members.id") Examples ~~~~~~~~ :: # returns all the lists (only name and id) client.lists.all(get_all=True, fields="lists.name,lists.id") # returns all members inside list '123456' client.lists.members.all('123456', get_all=True) # return the first 100 member's email addresses for the list with id 123456 client.lists.members.all('123456', count=100, offset=0, fields="members.email_address") # returns the list matching id '123456' client.lists.get('123456') # add John Doe with email john.doe@example.com to list matching id '123456' client.lists.members.create('123456', { 'email_address': 'john.doe@example.com', 'status': 'subscribed', 'merge_fields': { 'FNAME': 'John', 'LNAME': 'Doe', }, }) # returns all the campaigns client.campaigns.all(get_all=True) # You can also disable at runtime with the optional ``enabled`` parameter. # Every API call will return None client = MailChimp('YOUR SECRET KEY', enabled=False) # You are encouraged to specify a value in seconds for the ``timeout`` # parameter to avoid hanging requests. client = MailChimp('YOUR SECRET KEY', timeout=10.0) # You are encouraged to specify a User-Agent for requests to the MailChimp # API. Headers can be specified using the ``request_headers`` parameter. headers = requests.utils.default_headers() headers['User-Agent'] = 'Example (example@example.com)' client = MailChimp('YOUR SECRET KEY', request_headers=headers) API Structure ------------- All endpoints follow the structure listed in the official MailChimp API v3 documentation. The structure will be listed below and then the individual methods available after. :: MailChimp +- Root +- Authorized Apps +- Automations | +- Actions | +- Emails | | +- Actions | | +- Queues | +- Removed Subscribers +- Batch Operations +- Batch Webhooks +- Campaign Folders +- Campaigns | +- Actions | +- Content | +- Feedback | +- Send Checklist +- Conversations | +- Messages +- Customer Journeys +- Stores | +- Carts | | +- Lines | +- Customers | +- Orders | | +- Lines | +- Products | +- Images | +- Variants | +- Promo Rules | +- Promo Codes +- File Manager Files +- File Manager Folders +- Landing Pages | +- Actions | +- Content +- Lists | +- Abuse Reports | +- Activity | +- Clients | +- Growth History | +- Interest Categories | | +- Interests | +- Members | | +- Activity | | +- Events | | +- Goals | | +- Notes | | +- Tags | +- Merge Fields | +- Segments | | +- Segment Members | +- Signup Forms | +- Twitter Lead Generation Carts | +- Webhooks +- Ping +- Reports | +- Campaign Abuse | +- Campaign Advice | +- Campaign Open reports | +- Click Reports | | +- Members | +- Domain Performance | +- EepURL Reports | +- Email Activity | +- Google Analytics | +- Location | +- Sent To | +- Sub-Reports | +- Unsubscribes +- Search Campaigns +- Search Members +- Template Folders +- Templates +- Default Content API Endpoints ------------- Below is the list of all endpoints and the methods that can be called against them. Any endpoint that has a method that takes an ID argument (for example the app_id in the authorized_apps endpoint or the subscriber_hash in the list members endpoints) will record all IDs passed as well as those generated by methods that will only ever return a single result such as the create() method present on some endpoints. These stored attributes are only available at the level that they were passed or created at and must be passed again to interact with a lower or higher level such as accessing a list and then a member. The below code assumes that you have initialized the MailChimp class as listed above with the name ``client``. Root ~~~~ .. _root-1: Root ^^^^ :: client.root.get() Authorized Apps ~~~~~~~~~~~~~~~ .. _authorized-apps-1: Authorized Apps ^^^^^^^^^^^^^^^ :: client.authorized_apps.create(data={}) client.authorized_apps.all(get_all=False) client.authorized_apps.get(app_id='') Automations ~~~~~~~~~~~ .. _automations-1: Automations ^^^^^^^^^^^ :: client.automations.all(get_all=False) client.automations.get(workflow_id='') Automation Actions ^^^^^^^^^^^^^^^^^^ :: client.automations.actions.pause(workflow_id='') client.automations.actions.start(workflow_id='') Automation Emails ^^^^^^^^^^^^^^^^^ :: client.automations.emails.all(workflow_id='') client.automations.emails.get(workflow_id='', email_id='') Automation Email Actions ^^^^^^^^^^^^^^^^^^^^^^^^ :: client.automations.emails.actions.pause(workflow_id='', email_id='') client.automations.emails.actions.start(workflow_id='', email_id='') Automation Email Queues ^^^^^^^^^^^^^^^^^^^^^^^ :: client.automations.emails.queues.create(workflow_id='', email_id='', data={}) client.automations.emails.queues.all(workflow_id='', email_id='') client.automations.emails.queues.get(workflow_id='', email_id='', subscriber_hash='') Automation Removed Subscribers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :: client.automations.removed_subscribers.create(workflow_id='', data={}) client.automations.removed_subscribers.all(workflow_id='') Batch Operations ~~~~~~~~~~~~~~~~ .. _batch-operations-1: Batch Operations ^^^^^^^^^^^^^^^^ :: client.batch_operations.create(data={}) client.batch_operations.all(get_all=False) client.batch_operations.get(batch_id='') client.batch_operations.delete(batch_id='') Batch Webhooks ~~~~~~~~~~~~~~ .. _batch-webhooks-1: Batch Webhooks ^^^^^^^^^^^^^^ :: client.batch_webhooks.create(data={}) client.batch_webhooks.all(get_all=False) client.batch_webhooks.get(batch_webhook_id='') client.batch_webhooks.update(batch_webhook_id='', data={}) client.batch_webhooks.delete(batch_webhook_id='') Campaigns ~~~~~~~~~ Folders ^^^^^^^ :: client.campaign_folders.create(data={}) client.campaign_folders.all(get_all=False) client.campaign_folders.get(folder_id='') client.campaign_folders.update(folder_id='', data={}) client.campaign_folders.delete(folder_id='') .. _campaigns-1: Campaigns ^^^^^^^^^ :: client.campaigns.create(data={}) client.campaigns.all(get_all=False) client.campaigns.get(campaign_id='') client.campaigns.update(campaign_id='') client.campaigns.delete(campaign_id='') Campaign Actions ^^^^^^^^^^^^^^^^ :: client.campaigns.actions.cancel(campaign_id='') client.campaigns.actions.pause(campaign_id='') client.campaigns.actions.replicate(campaign_id='') client.campaigns.actions.resume(campaign_id='') client.campaigns.actions.schedule(campaign_id='', data={}) client.campaigns.actions.send(campaign_id='') client.campaigns.actions.resend(campaign_id='') client.campaigns.actions.test(campaign_id='', data={}) client.campaigns.actions.unschedule(campaign_id='') Campaign Content ^^^^^^^^^^^^^^^^ :: client.campaigns.content.get(campaign_id='') client.campaigns.content.update(campaign_id='', data={}) Campaign Feedback ^^^^^^^^^^^^^^^^^ :: client.campaigns.feedback.create(campaign_id='', data={}) client.campaigns.feedback.all(campaign_id='', get_all=False) client.campaigns.feedback.get(campaign_id='', feedback_id='') client.campaigns.feedback.update(campaign_id='', feedback_id='', data={}) client.campaigns.feedback.delete(campaign_id='', feedback_id='') Campaign Send Checklist ^^^^^^^^^^^^^^^^^^^^^^^ :: client.campaigns.send_checklist.get(campaign_id='') Conversations ~~~~~~~~~~~~~ .. _conversations-1: Conversations ^^^^^^^^^^^^^ :: client.conversations.all(get_all=False) client.conversations.get(conversation_id='') Conversation Messages ^^^^^^^^^^^^^^^^^^^^^ :: client.conversations.messages.create(conversation_id='', data={}) client.conversations.messages.all(conversation_id='') client.conversations.messages.get(conversation_id='', message_id='') Customer Journeys ~~~~~~~~~~~~~~~~~ .. _customer-journeys-1: Customer Journeys ^^^^^^^^^^^^^^^^^ :: client.customer_journeys.trigger(journey_id='', step_id='', data={}) E-Commerce ~~~~~~~~~~ Stores ^^^^^^ :: client.stores.create(data={}) client.stores.all(get_all=False) client.stores.get(store_id='') client.stores.update(store_id='', data={}) client.stores.delete(store_id='') Store Carts ^^^^^^^^^^^ :: client.stores.carts.create(store_id='', data={}) client.stores.carts.all(store_id='', get_all=False) client.stores.carts.get(store_id='', cart_id='') client.stores.carts.update(store_id='', cart_id='', data={}) client.stores.carts.delete(store_id='', cart_id='') Store Cart Lines ^^^^^^^^^^^^^^^^ :: client.stores.carts.lines.create(store_id='', cart_id='', data={}) client.stores.carts.lines.all(store_id='', cart_id='', get_all=False) client.stores.carts.lines.get(store_id='', cart_id='', line_id='') client.stores.carts.lines.update(store_id='', cart_id='', line_id='', data={}) client.stores.carts.lines.delete(store_id='', cart_id='', line_id='') Store Customers ^^^^^^^^^^^^^^^ :: client.stores.customers.create(store_id='', data={}) client.stores.customers.all(store_id='', get_all=False) client.stores.customers.get(store_id='', customer_id='') client.stores.customers.update(store_id='', customer_id='', data={}) client.stores.customers.create_or_update(store_id='', customer_id='', data={}) client.stores.customers.delete(store_id='', customer_id='') Store Orders ^^^^^^^^^^^^ :: client.stores.orders.create(store_id='', data={}) client.stores.orders.all(store_id='', get_all=False) client.stores.orders.get(store_id='', order_id='') client.stores.orders.update(store_id='', order_id='', data={}) client.stores.orders.delete(store_id='', order_id='') Store Order Lines ^^^^^^^^^^^^^^^^^ :: client.stores.orders.lines.create(store_id='', order_id='', data={}) client.stores.orders.lines.all(store_id='', order_id='', get_all=False) client.stores.orders.lines.get(store_id='', order_id='', line_id='') client.stores.orders.lines.update(store_id='', order_id='', line_id='', data={}) client.stores.orders.lines.delete(store_id='', order_id='', line_id='') Store Products ^^^^^^^^^^^^^^ :: client.stores.products.create(store_id='', data={}) client.stores.products.all(store_id='', get_all=False) client.stores.products.get(store_id='', product_id='') client.stores.products.update(store_id='', product_id='') client.stores.products.delete(store_id='', product_id='') Store Product Images ^^^^^^^^^^^^^^^^^^^^ :: client.stores.products.images.create(store_id='', product_id='', data={}) client.stores.products.images.all(store_id='', product_id='', get_all=False) client.stores.products.images.get(store_id='', product_id='', image_id='') client.stores.products.images.update(store_id='', product_id='', image_id='', data={}) client.stores.products.images.delete(store_id='', product_id='', image_id='') Store Product Variants ^^^^^^^^^^^^^^^^^^^^^^ :: client.stores.products.variants.create(store_id='', product_id='', data={}) client.stores.products.variants.all(store_id='', product_id='', get_all=False) client.stores.products.variants.get(store_id='', product_id='', variant_id='') client.stores.products.variants.update(store_id='', product_id='', variant_id='', data={}) client.stores.products.variants.create_or_update(store_id='', product_id='', variant_id='', data={}) client.stores.products.variants.delete(store_id='', product_id='', variant_id='') File Manager ~~~~~~~~~~~~ Files ^^^^^ :: client.files.create(data={}) client.files.all(get_all=False) client.files.get(file_id='') client.files.update(file_id='', data={}) client.files.delete(file_id='') .. _folders-1: Folders ^^^^^^^ :: client.folders.create(data={}) client.folders.all(get_all=False) client.folders.get(folder_id='') client.folders.update(folder_id='', data={}) client.folders.delete(folder_id='') Landing Pages ~~~~~~~~~~~~~ .. _landing-pages-1: Landing Pages ^^^^^^^^^^^^^ :: client.landing_pages.create(data={}) client.landing_pages.all() client.landing_pages.all(fields='') client.landing_pages.get(page_id='') client.landing_pages.update(page_id='', data={}) client.landing_pages.delete(page_id='') Landing Pages Actions ^^^^^^^^^^^^^^^^^^^^^ :: client.landing_pages.actions.publish(page_id='') client.landing_pages.actions.unpublish(page_id='') Landing Pages Content ^^^^^^^^^^^^^^^^^^^^^ :: client.landing_pages.content.get(page_id='') Lists ~~~~~ .. _lists-1: Lists ^^^^^ :: client.lists.create(data={}) client.lists.update_members(list_id='', data={}) client.lists.all(get_all=False) client.lists.get(list_id='') client.lists.update(list_id='', data={}) client.lists.delete(list_id='') List Abuse Reports ^^^^^^^^^^^^^^^^^^ :: client.lists.abuse_reports.all(list_id='', get_all=False) client.lists.abuse_reports.get(list_id='', report_id='') List Activity ^^^^^^^^^^^^^ :: client.lists.activity.all(list_id='', subscriber_hash='') client.lists.activity.feed(list_id='', subscriber_hash='') List Clients ^^^^^^^^^^^^ :: client.lists.clients.all(list_id='') List Growth History ^^^^^^^^^^^^^^^^^^^ :: client.lists.growth_history.all(list_id='', get_all=False) client.lists.growth_history.get(list_id='', month='') List Interest Categories ^^^^^^^^^^^^^^^^^^^^^^^^ :: client.lists.interest_categories.create(list_id='', data={}) client.lists.interest_categories.all(list_id='', get_all=False) client.lists.interest_categories.get(list_id='', category_id='') client.lists.interest_categories.update(list_id='', category_id='', data={}) client.lists.interest_categories.delete(list_id='', category_id='') List Interest Category Interests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :: client.lists.interest_categories.interests.create(list_id='', category_id='', data={}) client.lists.interest_categories.interests.all(list_id='', category_id='', get_all=False) client.lists.interest_categories.interests.get(list_id='', category_id='', interest_id='') client.lists.interest_categories.interests.update(list_id='', category_id='', interest_id='', data={}) client.lists.interest_categories.interests.delete(list_id='', category_id='', interest_id='') List Members ^^^^^^^^^^^^ :: client.lists.members.create(list_id='', data={}) client.lists.members.all(list_id='', get_all=False) client.lists.members.get(list_id='', subscriber_hash='') client.lists.members.update(list_id='', subscriber_hash='', data={}) client.lists.members.create_or_update(list_id='', subscriber_hash='', data={}) client.lists.members.delete(list_id='', subscriber_hash='') client.lists.members.delete_permanent(list_id='', subscriber_hash='') List Member Activity ^^^^^^^^^^^^^^^^^^^^ :: client.lists.members.activity.all(list_id='', subscriber_hash='') List Member Events ^^^^^^^^^^^^^^^^^^ :: client.lists.members.events.create(list_id='', subscriber_hash='', data={}) client.lists.members.events.all(list_id='', subscriber_hash='', get_all=False) List Member Goals ^^^^^^^^^^^^^^^^^ :: client.lists.members.goals.all(list_id='', subscriber_hash='') List Member Notes ^^^^^^^^^^^^^^^^^ :: client.lists.members.notes.create(list_id='', subscriber_hash='', data={}) client.lists.members.notes.all(list_id='', subscriber_hash='', get_all=False) client.lists.members.notes.get(list_id='', subscriber_hash='', note_id='') client.lists.members.notes.update(list_id='', subscriber_hash='', note_id='', data={}) client.lists.members.notes.delete(list_id='', subscriber_hash='', note_id='') List Member Tags ^^^^^^^^^^^^^^^^ :: client.lists.members.tags.update(list_id='', subscriber_hash='', data={}) client.lists.members.tags.all(list_id='', subscriber_hash='') List Merge Fields ^^^^^^^^^^^^^^^^^ :: client.lists.merge_fields.create(list_id='', data={}) client.lists.merge_fields.all(list_id='', get_all=False) client.lists.merge_fields.get(list_id='', merge_id='') client.lists.merge_fields.update(list_id='', merge_id='', data={}) client.lists.merge_fields.delete(list_id='', merge_id='') List Segments ^^^^^^^^^^^^^ :: client.lists.segments.create(list_id='', data={}) client.lists.segments.all(list_id='', get_all=False) client.lists.segments.get(list_id='', segment_id='') client.lists.segments.update(list_id='', segment_id='', data={}) client.lists.segments.update_members(list_id='', segment_id='', data={}) client.lists.segments.delete(list_id='', segment_id='') List Segment Members ^^^^^^^^^^^^^^^^^^^^ :: client.lists.segments.members.create(list_id='', segment_id='', data={}) client.lists.segments.members.all(list_id='', segment_id='', get_all=False) client.lists.segments.members.delete(list_id='', segment_id='', subscriber_hash='') List Signup Forms ^^^^^^^^^^^^^^^^^ :: client.lists.signup_forms.create(list_id='', data={}) client.lists.signup_forms.all(list_id='') List Webhooks ^^^^^^^^^^^^^ :: client.lists.webhooks.create(list_id='', data={}) client.lists.webhooks.all(list_id='') client.lists.webhooks.get(list_id='', webhook_id='') client.lists.webhooks.update(list_id='', webhook_id='', data={}) client.lists.webhooks.delete(list_id='', webhook_id='') Reports ~~~~~~~ .. _reports-1: Reports ^^^^^^^ :: client.reports.all(get_all=False) client.reports.get(campaign_id='') Campaign Abuse Reports ^^^^^^^^^^^^^^^^^^^^^^ :: client.reports.abuse_reports.all(campaign_id='') client.reports.abuse_reports.get(campaign_id='', report_id='') Campaign Advice ^^^^^^^^^^^^^^^ :: client.reports.advice.all(campaign_id='') Click Details Report ^^^^^^^^^^^^^^^^^^^^ :: client.reports.click_details.all(campaign_id='', get_all=False) client.reports.click_details.get(campaign_id='', link_id='') Click Details Report Members ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :: client.reports.click_details.members.all(campaign_id='', link_id='', get_all=False) client.reports.click_details.members.get(campaign_id='', link_id='', subscriber_hash='') Domain Performance Reports ^^^^^^^^^^^^^^^^^^^^^^^^^^ :: client.reports.domain_performance.all(campaign_id='') EepURL Reports ^^^^^^^^^^^^^^ :: client.reports.eepurl.all(camnpaign_id='') Email Activity Reports ^^^^^^^^^^^^^^^^^^^^^^ :: client.reports.email_activity.all(campaign_id='', get_all=False) client.reports.email_activity.get(campaign_id='', subscriber_hash='') Locations Report ^^^^^^^^^^^^^^^^ :: client.reports.locations.all(campaign_id='', get_all=False) Sent To Reports ^^^^^^^^^^^^^^^ :: client.reports.sent_to.all(campaign_id='', get_all=False) client.reports.sent_to.get(campaign_id='', subscriber_hash='') Sub-Reports ^^^^^^^^^^^ :: client.reports.subreports.all(campaign_id='') Unsubscribes ^^^^^^^^^^^^ :: client.reports.unsubscribes.all(campaign_id='', get_all=False) client.reports.unsubscribes.get(campaign_id='', subscriber_hash='') Search ~~~~~~ .. _campaigns-2: Campaigns ^^^^^^^^^ :: client.search_campaigns.get() Members ^^^^^^^ :: client.search_members.get() Templates ~~~~~~~~~ .. _folders-2: Folders ^^^^^^^ :: client.template_folders.create(data={}) client.template_folders.all(get_all=False) client.template_folders.get(folder_id='') client.template_folders.update(folder_id='', data={}) client.template_folders.delete(folder_id='') .. _templates-1: Templates ^^^^^^^^^ :: client.templates.create(data={}) client.templates.all(get_all=False) client.templates.get(template_id='') client.templates.update(template_id='', data={}) client.templates.delete(template_id='') Default Content ^^^^^^^^^^^^^^^ :: client.templates.default_content.all(template_id='') Logging ------- The MailChimp client will log request/response detail into the mailchimp3.client logging namespace. Consider the following snippet to get started with logging: .. code:: python import logging fh = logging.FileHandler('/path/to/some/log.log') logger = logging.getLogger('mailchimp3.client') logger.addHandler(fh) # use the client normally client.lists.all(**{'fields': 'lists.date_created'}) request/response detail will be appended into /path/to/some/log.log: :: GET Request: https://us15.api.mailchimp.com/3.0/lists?fields=lists.date_created GET Response: 200 {"lists":[{"date_created":"2017-05-10T13:53:05+00:00"},{"date_created":"2017-08-22T20:27:56+00:00"},{"date_created":"2017-05-12T21:22:15+00:00"},{"date_created":"2017-04-27T17:42:04+00:00"},{"date_created":"2017-05-10T14:14:49+00:00"},{"date_created":"2017-05-10T13:52:37+00:00"},{"date_created":"2017-05-10T13:51:40+00:00"}]} Check the `docs `__ for more detail on the Python logging package. Support ------- If you are having issues, please let us know or submit a pull request. License ------- The project is licensed under the MIT License. .. |mailchimp3 v3.0.21 on PyPi| image:: https://img.shields.io/pypi/v/mailchimp3.svg :target: https://pypi.python.org/pypi/mailchimp3 .. |MIT license| image:: https://img.shields.io/badge/licence-MIT-blue.svg .. |Stable| image:: https://img.shields.io/badge/status-stable-green.svg ================================================ FILE: mailchimp3/__init__.py ================================================ # coding=utf-8 """ Mailchimp v3 Api SDK Documentation at http://developer.mailchimp.com/documentation/mailchimp/reference/overview/ """ # API Client from mailchimp3.mailchimpclient import MailChimpClient # API Root from mailchimp3.entities.root import Root # Authorized Apps from mailchimp3.entities.authorizedapps import AuthorizedApps # Automations from mailchimp3.entities.automations import Automations from mailchimp3.entities.automationactions import AutomationActions from mailchimp3.entities.automationemails import AutomationEmails from mailchimp3.entities.automationemailactions import AutomationEmailActions from mailchimp3.entities.automationemailqueues import AutomationEmailQueues from mailchimp3.entities.automationremovedsubscribers import AutomationRemovedSubscribers # Batch Operations from mailchimp3.entities.batchoperations import BatchOperations # Batch Webhooks from mailchimp3.entities.batchwebhooks import BatchWebhooks # Campaign Folders from mailchimp3.entities.campaignfolders import CampaignFolders # Campaigns from mailchimp3.entities.campaigns import Campaigns from mailchimp3.entities.campaignactions import CampaignActions from mailchimp3.entities.campaigncontent import CampaignContent from mailchimp3.entities.campaignfeedback import CampaignFeedback from mailchimp3.entities.campaignsendchecklist import CampaignSendChecklist # Conversations from mailchimp3.entities.conversations import Conversations from mailchimp3.entities.conversationmessages import ConversationMessages # Customer Journeys from mailchimp3.entities.customerjourney import CustomerJourney # E-commerce Stores from mailchimp3.entities.stores import Stores from mailchimp3.entities.storecarts import StoreCarts from mailchimp3.entities.storecartlines import StoreCartLines from mailchimp3.entities.storecustomers import StoreCustomers from mailchimp3.entities.storeorders import StoreOrders from mailchimp3.entities.storeorderlines import StoreOrderLines from mailchimp3.entities.storeproducts import StoreProducts from mailchimp3.entities.storeproductimages import StoreProductImages from mailchimp3.entities.storeproductvariants import StoreProductVariants from mailchimp3.entities.storepromorules import StorePromoRules from mailchimp3.entities.storepromocodes import StorePromoCodes # File Manager Files from mailchimp3.entities.filemanagerfiles import FileManagerFiles # File Manager Folders from mailchimp3.entities.filemanagerfolders import FileManagerFolders # Landinge Pages from mailchimp3.entities.landingpages import LandingPages from mailchimp3.entities.landingpageaction import LandingPageAction from mailchimp3.entities.landingpagecontent import LandingPageContent # Lists from mailchimp3.entities.lists import Lists from mailchimp3.entities.listabusereports import ListAbuseReports from mailchimp3.entities.listactivity import ListActivity from mailchimp3.entities.listclients import ListClients from mailchimp3.entities.listgrowthhistory import ListGrowthHistory from mailchimp3.entities.listinterestcategories import ListInterestCategories from mailchimp3.entities.listinterestcategoryinterest import ListInterestCategoryInterest from mailchimp3.entities.listmembers import ListMembers from mailchimp3.entities.listmemberactivity import ListMemberActivity from mailchimp3.entities.listmemberevents import ListMemberEvents from mailchimp3.entities.listmembergoals import ListMemberGoals from mailchimp3.entities.listmembernotes import ListMemberNotes from mailchimp3.entities.listmembertags import ListMemberTags from mailchimp3.entities.listmergefields import ListMergeFields from mailchimp3.entities.listsegments import ListSegments from mailchimp3.entities.listsegmentmembers import ListSegmentMembers from mailchimp3.entities.listsignupforms import ListSignupForms from mailchimp3.entities.listwebhooks import ListWebhooks # ping from mailchimp3.entities.ping import Ping # Reports from mailchimp3.entities.reports import Reports from mailchimp3.entities.reportcampaignabusereports import ReportCampaignAbuseReports from mailchimp3.entities.reportcampaignadvice import ReportCampaignAdvice from mailchimp3.entities.reportclickdetailreports import ReportClickDetailReports from mailchimp3.entities.reportclickdetailmembers import ReportClickDetailMembers from mailchimp3.entities.reportdomainperformance import ReportDomainPerformance from mailchimp3.entities.reporteepurl import ReportEepURL from mailchimp3.entities.reportemailactivity import ReportEmailActivity from mailchimp3.entities.reportlocations import ReportLocations from mailchimp3.entities.reportsentto import ReportSentTo from mailchimp3.entities.reportsubreports import ReportSubReports from mailchimp3.entities.reportunsubscribes import ReportUnsubscribes from mailchimp3.entities.reportopendetails import ReportOpenDetails from mailchimp3.entities.reportgoogleanalytics import ReportGoogleAnalytics # Search Campaigns from mailchimp3.entities.searchcampaigns import SearchCampaigns # Search Members from mailchimp3.entities.searchmembers import SearchMembers # Template Folders from mailchimp3.entities.templatefolders import TemplateFolders # Templates from mailchimp3.entities.templates import Templates from mailchimp3.entities.templatedefaultcontent import TemplateDefaultContent class MailChimp(MailChimpClient): """ MailChimp class to communicate with the v3 API """ def __init__(self, *args, **kwargs): """ Initialize the class with your api_key and user_id and attach all of the endpoints """ super(MailChimp, self).__init__(*args, **kwargs) # API Root self.root = self.api_root = Root(self) # Authorized Apps self.authorized_apps = AuthorizedApps(self) # Automations - Paid feature self.automations = Automations(self) self.automations.actions = AutomationActions(self) self.automations.emails = AutomationEmails(self) self.automations.emails.actions = AutomationEmailActions(self) self.automations.emails.queues = AutomationEmailQueues(self) self.automations.removed_subscribers = AutomationRemovedSubscribers(self) # Batch Operations self.batches = self.batch_operations = BatchOperations(self) # Batch Webhooks self.batch_webhooks = BatchWebhooks(self) # Campaign Folders self.campaign_folders = CampaignFolders(self) # Campaigns self.campaigns = Campaigns(self) self.campaigns.actions = CampaignActions(self) self.campaigns.content = CampaignContent(self) self.campaigns.feedback = CampaignFeedback(self) self.campaigns.send_checklist = CampaignSendChecklist(self) # Conversations - Paid feature self.conversations = Conversations(self) self.conversations.messages = ConversationMessages(self) # Customer Journey self.journeys = self.customer_journeys = CustomerJourney(self) # E-commerce Stores self.stores = self.ecommerce = Stores(self) self.stores.carts = StoreCarts(self) self.stores.carts.lines = StoreCartLines(self) self.stores.customers = StoreCustomers(self) self.stores.orders = StoreOrders(self) self.stores.orders.lines = StoreOrderLines(self) self.stores.products = StoreProducts(self) self.stores.products.images = StoreProductImages(self) self.stores.products.variants = StoreProductVariants(self) self.stores.promo_rules = StorePromoRules(self) self.stores.promo_codes = StorePromoCodes(self) # File Manager Files self.files = FileManagerFiles(self) # File Manager Folders self.folders = FileManagerFolders(self) # Landinge Pages self.landing_pages = LandingPages(self) self.landing_pages.actions = LandingPageAction(self) self.landing_pages.content = LandingPageContent(self) # Lists self.lists = Lists(self) self.lists.abuse_reports = ListAbuseReports(self) self.lists.activity = ListActivity(self) self.lists.clients = ListClients(self) self.lists.growth_history = ListGrowthHistory(self) self.lists.interest_categories = ListInterestCategories(self) self.lists.interest_categories.interests = ListInterestCategoryInterest(self) self.lists.members = ListMembers(self) self.lists.members.activity = ListMemberActivity(self) self.lists.members.events = ListMemberEvents(self) self.lists.members.goals = ListMemberGoals(self) self.lists.members.notes = ListMemberNotes(self) self.lists.members.tags = ListMemberTags(self) self.lists.merge_fields = ListMergeFields(self) self.lists.segments = ListSegments(self) self.lists.segments.members = ListSegmentMembers(self) self.lists.signup_forms = ListSignupForms(self) self.lists.webhooks = ListWebhooks(self) # Ping self.ping = Ping(self) # Reports self.reports = Reports(self) self.reports.abuse_reports = ReportCampaignAbuseReports(self) self.reports.advice = ReportCampaignAdvice(self) self.reports.click_details = ReportClickDetailReports(self) self.reports.click_details.members = ReportClickDetailMembers(self) self.reports.domain_performance = ReportDomainPerformance(self) self.reports.eepurl = ReportEepURL(self) self.reports.email_activity = ReportEmailActivity(self) self.reports.locations = ReportLocations(self) self.reports.sent_to = ReportSentTo(self) self.reports.subreports = ReportSubReports(self) self.reports.unsubscribes = ReportUnsubscribes(self) self.reports.open_details = ReportOpenDetails(self) self.reports.google_analytics = ReportGoogleAnalytics(self) # Search Campaigns self.search_campaigns = SearchCampaigns(self) # Search Members self.search_members = SearchMembers(self) # Template Folders self.template_folders = TemplateFolders(self) # Templates self.templates = Templates(self) self.templates.default_content = TemplateDefaultContent(self) ================================================ FILE: mailchimp3/baseapi.py ================================================ # coding=utf-8 """ The base API object that allows constructions of various endpoint paths """ from __future__ import unicode_literals from itertools import chain from mailchimp3.helpers import merge_results class BaseApi(object): """ Simple class to buid path for entities """ def __init__(self, mc_client): """ Initialize the class with you user_id and secret_key :param mc_client: The mailchimp client connection :type mc_client: :mod:`mailchimp3.mailchimpclient.MailChimpClient` """ super(BaseApi, self).__init__() self._mc_client = mc_client self.endpoint = '' def _build_path(self, *args): """ Build path with endpoint and args :param args: Tokens in the endpoint URL :type args: :py:class:`unicode` """ return '/'.join(chain((self.endpoint,), map(str, args))) def _iterate(self, url, **queryparams): """ Iterate over all pages for the given url. Feed in the result of self._build_path as the url. :param url: The url of the endpoint :type url: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ # fields as a query string parameter should be a string with # comma-separated substring values to pass along to # self._mc_client._get(). It should also contain total_items whenever # the parameter is employed, which is forced here. if not self._mc_client.enabled: return if 'fields' in queryparams: if 'total_items' not in queryparams['fields'].split(','): queryparams['fields'] += ',total_items' # Remove offset if provided in queryparams to avoid 'multiple values # for keyword argument' TypeError queryparams.pop("offset", None) # Fetch results from mailchimp, up to first count. If count is not # provided, return a count of 500. The maximum value supported by the # api is 1000, but such a large request can cause 504 errors. See: # https://github.com/VingtCinq/python-mailchimp/pull/207 count = queryparams.pop("count", 500) result = self._mc_client._get(url=url, offset=0, count=count, **queryparams) total = result['total_items'] # Fetch further results if necessary if total > count: for offset in range(1, int(total / count) + 1): result = merge_results(result, self._mc_client._get( url=url, offset=int(offset * count), count=count, **queryparams )) return result else: # Further results not necessary return result ================================================ FILE: mailchimp3/entities/__init__.py ================================================ ================================================ FILE: mailchimp3/entities/authorizedapps.py ================================================ # coding=utf-8 """ The Authorized Apps endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/authorized-apps/ Schema: http://api.mailchimp.com/schema/3.0/AuthorizedApps/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class AuthorizedApps(BaseApi): """ Manage registered, connected apps for your MailChimp account with the Authorized Apps endpoints. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AuthorizedApps, self).__init__(*args, **kwargs) self.endpoint = 'authorized-apps' self.app_id = None def create(self, data): """ Retrieve OAuth2-based credentials to associate API calls with your application. :param data: The request body parameters :type data: :py:class:`dict` data = { "client_id": string*, "client_secret": string* } """ self.app_id = None if 'client_id' not in data: raise KeyError('The authorized app must have a client_id') if 'client_secret' not in data: raise KeyError('The authorized app must have a client_secret') return self._mc_client._post(url=self._build_path(), data=data) def all(self, get_all=False, **queryparams): """ Get a list of an account’s registered, connected applications. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.app_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, app_id, **queryparams): """ Get information about a specific authorized application :param app_id: The unique id for the connected authorized application :type app_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.app_id = app_id return self._mc_client._get(url=self._build_path(app_id), **queryparams) ================================================ FILE: mailchimp3/entities/automationactions.py ================================================ # coding=utf-8 """ The Automations API endpoint actions Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class AutomationActions(BaseApi): """ Actions for the Automations endpoint. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AutomationActions, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None # Paid feature def pause(self, workflow_id): """ Pause all emails in a specific Automation workflow. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` """ self.workflow_id = workflow_id return self._mc_client._post(url=self._build_path(workflow_id, 'actions/pause-all-emails')) # Paid feature def start(self, workflow_id): """ Start all emails in an Automation workflow. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` """ self.workflow_id = workflow_id return self._mc_client._post(url=self._build_path(workflow_id, 'actions/start-all-emails')) ================================================ FILE: mailchimp3/entities/automationemailactions.py ================================================ # coding=utf-8 """ The Automation Emails endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/emails/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class AutomationEmailActions(BaseApi): """ Manage individual emails in an Automation workflow. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AutomationEmailActions, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None self.email_id = None # Paid feature def pause(self, workflow_id, email_id): """ Pause an automated email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` """ self.workflow_id = workflow_id self.email_id = email_id return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/pause')) # Paid feature def start(self, workflow_id, email_id): """ Start an automated email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` """ self.workflow_id = workflow_id self.email_id = email_id return self._mc_client._post(url=self._build_path(workflow_id, 'emails', email_id, 'actions/start')) #Paid feature def delete(self, workflow_id, email_id): """ Removes an individual Automation workflow email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` """ self.workflow_id = workflow_id self.email_id = email_id return self._mc_client._delete(url=self._build_path(workflow_id, 'emails', email_id)) ================================================ FILE: mailchimp3/entities/automationemailqueues.py ================================================ # coding=utf-8 """ The Automation Email Queue endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/emails/queue/ Schema: https://api.mailchimp.com/schema/3.0/Automations/Emails/Queue/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email, check_subscriber_hash class AutomationEmailQueues(BaseApi): """ Manage list member queues for Automation emails. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AutomationEmailQueues, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None self.email_id = None self.subscriber_hash = None # Paid feature def create(self, workflow_id, email_id, data): """ Manually add a subscriber to a workflow, bypassing the default trigger settings. You can also use this endpoint to trigger a series of automated emails in an API 3.0 workflow type or add subscribers to an automated email queue that uses the API request delay type. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string* } """ self.workflow_id = workflow_id self.email_id = email_id if 'email_address' not in data: raise KeyError('The automation email queue must have an email_address') check_email(data['email_address']) response = self._mc_client._post( url=self._build_path(workflow_id, 'emails', email_id, 'queue'), data=data ) if response is not None: self.subscriber_hash = response['id'] else: self.subscriber_hash = None return response # Paid feature def all(self, workflow_id, email_id): """ Get information about an Automation email queue. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` """ self.workflow_id = workflow_id self.email_id = email_id self.subscriber_hash = None return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue')) # Paid feature def get(self, workflow_id, email_id, subscriber_hash): """ Get information about a specific subscriber in an Automation email queue. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.workflow_id = workflow_id self.email_id = email_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id, 'queue', subscriber_hash)) ================================================ FILE: mailchimp3/entities/automationemails.py ================================================ # coding=utf-8 """ The Automation Emails endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/emails/ Schema: https://api.mailchimp.com/schema/3.0/Automations/Emails/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.automationemailactions import AutomationEmailActions from mailchimp3.entities.automationemailqueues import AutomationEmailQueues class AutomationEmails(BaseApi): """ Manage individual emails in an Automation workflow. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AutomationEmails, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None self.email_id = None self.actions = AutomationEmailActions(self) self.queues = AutomationEmailQueues(self) # Paid feature def all(self, workflow_id, get_all=False, **queryparams): """ Get a summary of the emails in an Automation workflow. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: the query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.workflow_id = workflow_id self.email_id = None if get_all: return self._iterate(url=self._build_path(workflow_id, 'emails'), **queryparams) else: return self._mc_client._get(url=self._build_path(workflow_id, 'emails'), **queryparams) # Paid feature def get(self, workflow_id, email_id): """ Get information about an individual Automation workflow email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_id: :py:class:`str` """ self.workflow_id = workflow_id self.email_id = email_id return self._mc_client._get(url=self._build_path(workflow_id, 'emails', email_id)) ================================================ FILE: mailchimp3/entities/automationremovedsubscribers.py ================================================ # coding=utf-8 """ The Automation Removed Subscribers endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/removed-subscribers/ Schema: https://api.mailchimp.com/schema/3.0/Automations/RemovedSubscribers/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email class AutomationRemovedSubscribers(BaseApi): """ Remove subscribers from an Automation workflow. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(AutomationRemovedSubscribers, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None # Paid feature def create(self, workflow_id, data): """ Remove a subscriber from a specific Automation workflow. You can remove a subscriber at any point in an Automation workflow, regardless of how many emails they’ve been sent from that workflow. Once they’re removed, they can never be added back to the same workflow. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string* } """ self.workflow_id = workflow_id if 'email_address' not in data: raise KeyError('The automation removed subscriber must have an email_address') check_email(data['email_address']) return self._mc_client._post(url=self._build_path(workflow_id, 'removed-subscribers'), data=data) # Paid feature def all(self, workflow_id): """ Get information about subscribers who were removed from an Automation workflow. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` """ self.workflow_id = workflow_id return self._mc_client._get(url=self._build_path(workflow_id, 'removed-subscribers')) ================================================ FILE: mailchimp3/entities/automations.py ================================================ # coding=utf-8 """ The Automations API endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/ Schema: https://api.mailchimp.com/schema/3.0/Automations/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.automationactions import AutomationActions from mailchimp3.entities.automationemails import AutomationEmails from mailchimp3.entities.automationremovedsubscribers import AutomationRemovedSubscribers class Automations(BaseApi): """ Automation is a paid feature that lets you build a series of triggered emails that are sent to subscribers over a set period of time. Use the Automation API calls to manage Automation workflows, emails, and queues. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Automations, self).__init__(*args, **kwargs) self.endpoint = 'automations' self.workflow_id = None self.actions = AutomationActions(self) self.emails = AutomationEmails(self) self.removed_subscribers = AutomationRemovedSubscribers(self) # Paid feature def all(self, get_all=False, **queryparams): """ Get a summary of an account’s Automations. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: the query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.workflow_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) # Paid feature def get(self, workflow_id, **queryparams): """ Get a summary of an individual Automation workflow’s settings and content. The trigger_settings object returns information for the first email in the workflow. :param workflow_id: The unique id for the Automation workflow :type workflow_id: :py:class:`str` :param queryparams: the query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.workflow_id = workflow_id return self._mc_client._get(url=self._build_path(workflow_id), **queryparams) ================================================ FILE: mailchimp3/entities/batchoperations.py ================================================ # coding=utf-8 """ The Batch Operations API Endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/batches/ Schema: https://api.mailchimp.com/schema/3.0/Batches/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class BatchOperations(BaseApi): """ Use batch operations to complete multiple operations with a single call. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(BatchOperations, self).__init__(*args, **kwargs) self.endpoint = 'batches' self.batch_id = None self.operation_status = None def create(self, data): """ Begin processing a batch operations request. :param data: The request body parameters :type data: :py:class:`dict` data = { "operations": array* [ { "method": string* (Must be one of "GET", "POST", "PUT", "PATCH", or "DELETE") "path": string*, } ] } """ if 'operations' not in data: raise KeyError('The batch must have operations') for op in data['operations']: if 'method' not in op: raise KeyError('The batch operation must have a method') if op['method'] not in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']: raise ValueError('The batch operation method must be one of "GET", "POST", "PUT", "PATCH", ' 'or "DELETE", not {0}'.format(op['method'])) if 'path' not in op: raise KeyError('The batch operation must have a path') return self._mc_client._post(url=self._build_path(), data=data) def all(self, get_all=False, **queryparams): """ Get a summary of batch requests that have been made. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.batch_id = None self.operation_status = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, batch_id, **queryparams): """ Get the status of a batch request. :param batch_id: The unique id for the batch operation. :type batch_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.batch_id = batch_id self.operation_status = None return self._mc_client._get(url=self._build_path(batch_id), **queryparams) def delete(self, batch_id): """ Stops a batch request from running. Since only one batch request is run at a time, this can be used to cancel a long running request. The results of any completed operations will not be available after this call. :param batch_id: The unique id for the batch operation. :type batch_id: :py:class:`str` """ self.batch_id = batch_id self.operation_status = None return self._mc_client._delete(url=self._build_path(batch_id)) ================================================ FILE: mailchimp3/entities/batchwebhooks.py ================================================ # coding=utf-8 """ The Batch Webhooks API Endpoint Documentation: https://developer.mailchimp.com/documentation/mailchimp/reference/batch-webhooks/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class BatchWebhooks(BaseApi): """ Manage webhooks for batch operations. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(BatchWebhooks, self).__init__(*args, **kwargs) self.endpoint = 'batch-webhooks' self.batch_webhook_id = None def create(self, data): """ Configure a webhook that will fire whenever any batch request completes processing. :param data: The request body parameters :type data: :py:class:`dict` data = { "url": string* } """ if 'url' not in data: raise KeyError('The batch webhook must have a valid url') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.batch_webhook_id = response['id'] else: self.batch_webhook_id = None return response def all(self, get_all=False, **queryparams): """ Get all webhooks that have been configured for batches. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.batch_webhook_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, batch_webhook_id, **queryparams): """ Get information about a specific batch webhook. :param batch_webhook_id: The unique id for the batch webhook. :type batch_webhook_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.batch_webhook_id = batch_webhook_id return self._mc_client._get(url=self._build_path(batch_webhook_id), **queryparams) def update(self, batch_webhook_id, data): """ Update a webhook that will fire whenever any batch request completes processing. :param batch_webhook_id: The unique id for the batch webhook. :type batch_webhook_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "url": string* } """ self.batch_webhook_id = batch_webhook_id if 'url' not in data: raise KeyError('The batch webhook must have a valid url') return self._mc_client._patch(url=self._build_path(batch_webhook_id), data=data) def delete(self, batch_webhook_id): """ Remove a batch webhook. Webhooks will no longer be sent to the given URL. :param batch_webhook_id: The unique id for the batch webhook. :type batch_webhook_id: :py:class:`str` """ self.batch_webhook_id = batch_webhook_id return self._mc_client._delete(url=self._build_path(batch_webhook_id)) ================================================ FILE: mailchimp3/entities/campaignactions.py ================================================ # coding=utf-8 """ The Campaigns API actions endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/ Schema: https://api.mailchimp.com/schema/3.0/CampaignFolders/Instance.json """ from __future__ import unicode_literals from datetime import timedelta from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email class CampaignActions(BaseApi): """ Campaigns are how you send emails to your MailChimp list. Use the Campaigns API calls to manage campaigns in your MailChimp account. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CampaignActions, self).__init__(*args, **kwargs) self.endpoint = 'campaigns' self.campaign_id = None # Pro feature def cancel(self, campaign_id): """ Cancel a Regular or Plain-Text Campaign after you send, before all of your recipients receive it. This feature is included with MailChimp Pro. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/cancel-send')) def pause(self, campaign_id): """ Pause an RSS-Driven campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/pause')) def replicate(self, campaign_id): """ Replicate a campaign in saved or send status. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/replicate')) def resume(self, campaign_id): """ Resume an RSS-Driven campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/resume')) def schedule(self, campaign_id, data): """ Schedule a campaign for delivery. If you’re using Multivariate Campaigns to test send times or sending RSS Campaigns, use the send action instead. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "schedule_time": datetime* (A UTC timezone datetime that ends on the quarter hour [:00, :15, :30, or :45]) } """ if not data['schedule_time']: raise ValueError('You must supply a schedule_time') else: if data['schedule_time'].tzinfo is None: raise ValueError('The schedule_time must be in UTC') else: if data['schedule_time'].tzinfo.utcoffset(None) != timedelta(0): raise ValueError('The schedule_time must be in UTC') if data['schedule_time'].minute not in [0, 15, 30, 45]: raise ValueError('The schedule_time must end on the quarter hour (00, 15, 30, 45)') data['schedule_time'] = data['schedule_time'].strftime('%Y-%m-%dT%H:%M:00+00:00') self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/schedule'), data=data) def send(self, campaign_id): """ Send a MailChimp campaign. For RSS Campaigns, the campaign will send according to its schedule. All other campaigns will send immediately. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/send')) def resend(self, campaign_id): """ Creates a Resend to Non-Openers version of this campaign. We will also check if this campaign meets the criteria for Resend to Non-Openers campaigns. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/create-resend')) def test(self, campaign_id, data): """ Send a test email. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "test_emails": array*, "send_type": string* (Must be one of "html" or "plaintext") } """ for email in data['test_emails']: check_email(email) if data['send_type'] not in ['html', 'plaintext']: raise ValueError('The send_type must be either "html" or "plaintext"') self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/test'), data=data) def unschedule(self, campaign_id): """ Unschedule a scheduled campaign that hasn’t started sending. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/unschedule')) ================================================ FILE: mailchimp3/entities/campaigncontent.py ================================================ # coding=utf-8 """ The Campaign Content API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/content/ Schema: https://api.mailchimp.com/schema/3.0/Campaigns/Content/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class CampaignContent(BaseApi): """ Manage the HTML, plain-text, and template content for your MailChimp campaigns. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CampaignContent, self).__init__(*args, **kwargs) self.endpoint = 'campaigns' self.campaign_id = None def get(self, campaign_id, **queryparams): """ Get the the HTML and plain-text content for a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'content'), **queryparams) def update(self, campaign_id, data): """ Set the content for a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.campaign_id = campaign_id return self._mc_client._put(url=self._build_path(campaign_id, 'content'), data=data) ================================================ FILE: mailchimp3/entities/campaignfeedback.py ================================================ # coding=utf-8 """ The Campaign Feedback API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/feedback/ Schema: https://api.mailchimp.com/schema/3.0/Campaigns/Feedback/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class CampaignFeedback(BaseApi): """ Post comments, reply to team feedback, and send test emails while you’re working together on a MailChimp campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CampaignFeedback, self).__init__(*args, **kwargs) self.endpoint = 'campaigns' self.campaign_id = None self.feedback_id = None def create(self, campaign_id, data, **queryparams): """ Add feedback on a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "message": string* } :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id if 'message' not in data: raise KeyError('The campaign feedback must have a message') response = self._mc_client._post(url=self._build_path(campaign_id, 'feedback'), data=data, **queryparams) if response is not None: self.feedback_id = response['feedback_id'] else: self.feedback_id = None return response def all(self, campaign_id, get_all=False, **queryparams): """ Get team feedback while you’re working together on a MailChimp campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.feedback_id = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'feedback'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'feedback'), **queryparams) def get(self, campaign_id, feedback_id, **queryparams): """ Get a specific feedback message from a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param feedback_id: The unique id for the feedback message. :type feedback_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.feedback_id = feedback_id return self._mc_client._get(url=self._build_path(campaign_id, 'feedback', feedback_id), **queryparams) def update(self, campaign_id, feedback_id, data): """ Update a specific feedback message for a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param feedback_id: The unique id for the feedback message. :type feedback_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "message": string* } """ self.campaign_id = campaign_id self.feedback_id = feedback_id if 'message' not in data: raise KeyError('The campaign feedback must have a message') return self._mc_client._patch(url=self._build_path(campaign_id, 'feedback', feedback_id), data=data) def delete(self, campaign_id, feedback_id): """ Remove a specific feedback message for a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param feedback_id: The unique id for the feedback message. :type feedback_id: :py:class:`str` """ self.campaign_id = campaign_id self.feedback_id = feedback_id return self._mc_client._delete(url=self._build_path(campaign_id, 'feedback', feedback_id)) ================================================ FILE: mailchimp3/entities/campaignfolders.py ================================================ # coding=utf-8 """ The Campaign Folders API endpoints Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaign-folders/ Schema: https://api.mailchimp.com/schema/3.0/CampaignFolders/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class CampaignFolders(BaseApi): """ Organize your campaigns using folders. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CampaignFolders, self).__init__(*args, **kwargs) self.endpoint = 'campaign-folders' self.folder_id = None def create(self, data): """ Create a new campaign folder. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ if 'name' not in data: raise KeyError('The campaign folder must have a name') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.folder_id = response['id'] else: self.folder_id = None return response def all(self, get_all=False, **queryparams): """ Get all folders used to organize campaigns. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.folder_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, folder_id, **queryparams): """ Get information about a specific folder used to organize campaigns. :param folder_id: The unique id for the campaign folder. :type folder_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.folder_id = folder_id return self._mc_client._get(url=self._build_path(folder_id), **queryparams) def update(self, folder_id, data): """ Update a specific folder used to organize campaigns. :param folder_id: The unique id for the campaign folder. :type folder_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.folder_id = folder_id if 'name' not in data: raise KeyError('The campaign folder must have a name') return self._mc_client._patch(url=self._build_path(folder_id), data=data) def delete(self, folder_id): """ Delete a specific campaign folder, and mark all the campaigns in the folder as ‘unfiled’. :param folder_id: The unique id for the campaign folder. :type folder_id: :py:class:`str` """ self.folder_id = folder_id return self._mc_client._delete(url=self._build_path(folder_id)) ================================================ FILE: mailchimp3/entities/campaigns.py ================================================ # coding=utf-8 """ The Campaigns API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/ Schema: https://api.mailchimp.com/schema/3.0/Campaigns/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.campaignactions import CampaignActions from mailchimp3.entities.campaigncontent import CampaignContent from mailchimp3.entities.campaignfeedback import CampaignFeedback from mailchimp3.entities.campaignsendchecklist import CampaignSendChecklist from mailchimp3.helpers import check_email class Campaigns(BaseApi): """ Campaigns are how you send emails to your MailChimp list. Use the Campaigns API calls to manage campaigns in your MailChimp account. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Campaigns, self).__init__(*args, **kwargs) self.endpoint = 'campaigns' self.campaign_id = None self.actions = CampaignActions(self) self.content = CampaignContent(self) self.feedback = CampaignFeedback(self) self.send_checklist = CampaignSendChecklist(self) def create(self, data): """ Create a new MailChimp campaign. The ValueError raised by an invalid type in data does not mention 'absplit' as a potential value because the documentation indicates that the absplit type has been deprecated. :param data: The request body parameters :type data: :py:class:`dict` data = { "recipients": object* { "list_id": string* }, "variate_settings": object* (Required if type is "variate") { "subject_lines": string* (can be empty if subject_line in settings) "from_names": string* (can be empty if from_name in settings) "reply_to_addresses": string* (can be empty if reply_to in settings) "winner_criteria": string* (Must be one of "opens", "clicks", "total_revenue", or "manual") }, "rss_opts": object* (Required if type is "rss") { "feed_url": string*, "frequency": string* (Must be one of "daily", "weekly", or "monthly") }, "type": string* (Must be one of "regular", "plaintext", "rss", "variate", or "absplit") } """ if 'recipients' not in data: raise KeyError('The campaign must have recipients') if 'list_id' not in data['recipients']: raise KeyError('The campaign recipients must have a list_id') if 'reply_to' in data.get('settings', {}): check_email(data['settings']['reply_to']) if 'type' not in data: raise KeyError('The campaign must have a type') if not data['type'] in ['regular', 'plaintext', 'rss', 'variate', 'abspilt']: raise ValueError('The campaign type must be one of "regular", "plaintext", "rss", or "variate"') if data['type'] == 'variate': if 'variate_settings' not in data: raise KeyError('The variate campaign must have variate_settings') if 'winner_criteria' not in data['variate_settings']: raise KeyError('The campaign variate_settings must have a winner_criteria') if data['variate_settings']['winner_criteria'] not in ['opens', 'clicks', 'total_revenue', 'manual']: raise ValueError('The campaign variate_settings ' 'winner_criteria must be one of "opens", "clicks", "total_revenue", or "manual"') if 'subject_lines' not in data['variate_settings'] and 'subject_line' not in data.get('settings'): raise KeyError('The campaign variate_settings must have a subject_lines') if 'from_names' not in data['variate_settings'] and 'from_name' not in data.get('settings'): raise KeyError('The campaign variate_settings must have a from_names') if 'reply_to_addresses' not in data['variate_settings'] and 'reply_to' not in data.get('settings'): raise KeyError('The campaign variate_settings must have a reply_to_addresses') if data['type'] == 'rss': if 'rss_opts' not in data: raise KeyError('The rss campaign must have rss_opts') if 'feed_url' not in data['rss_opts']: raise KeyError('The campaign rss_opts must have a feed_url') if not data['rss_opts']['frequency'] in ['daily', 'weekly', 'monthly']: raise ValueError('The rss_opts frequency must be one of "daily", "weekly", or "monthly"') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.campaign_id = response['id'] else: self.campaign_id = None return response def all(self, get_all=False, **queryparams): """ Get all campaigns in an account. .. note:: The before_create_time, since_create_time, before_send_time, and since_send_time queryparams expect times to be listed in the ISO 8601 format in UTC (ex. 2015-10-21T15:41:36+00:00). :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = [] queryparams['status'] = [] queryparams['before_send_time'] = string queryparams['since_send_time'] = string queryparams['before_create_time'] = string queryparams['since_create_time'] = string queryparams['list_id'] = string queryparams['folder_id'] = string queryparams['sort_field'] = string queryparams['sort_dir'] = string """ self.campaign_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, campaign_id, **queryparams): """ Get information about a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['sort_field'] = string queryparams['create_time'] = string """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id), **queryparams) def update(self, campaign_id, data): """ Update some or all of the settings for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "settings": object* { "subject_line": string*, "from_name": string*, "reply_to": string* }, } """ self.campaign_id = campaign_id if 'settings' not in data: raise KeyError('The campaign must have settings') if 'subject_line' not in data['settings']: raise KeyError('The campaign settings must have a subject_line') if 'from_name' not in data['settings']: raise KeyError('The campaign settings must have a from_name') if 'reply_to' not in data['settings']: raise KeyError('The campaign settings must have a reply_to') check_email(data['settings']['reply_to']) return self._mc_client._patch(url=self._build_path(campaign_id), data=data) def delete(self, campaign_id): """ Remove a campaign from your MailChimp account. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._delete(url=self._build_path(campaign_id)) ================================================ FILE: mailchimp3/entities/campaignsendchecklist.py ================================================ # coding=utf-8 """ The Campaign Send Checklist API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/send-checklist/ Schema: https://api.mailchimp.com/schema/3.0/Campaigns/Checklist/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class CampaignSendChecklist(BaseApi): """ Review the send checklist for your campaign, and resolve any issues before sending. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CampaignSendChecklist, self).__init__(*args, **kwargs) self.endpoint = 'campaigns' self.campaign_id = None def get(self, campaign_id, **queryparams): """ Review the send checklist for a campaign, and resolve any issues before sending. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'send-checklist'), **queryparams) ================================================ FILE: mailchimp3/entities/conversationmessages.py ================================================ # coding=utf-8 """ The Conversation Messages API endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/conversations/messages/ Schema: https://api.mailchimp.com/schema/3.0/Conversations/Messages/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email class ConversationMessages(BaseApi): """ Manage messages in a specific campaign conversation. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ConversationMessages, self).__init__(*args, **kwargs) self.endpoint = 'conversations' self.conversation_id = None self.message_id = None # Paid feature def create(self, conversation_id, data): """ Post a new message to a conversation. :param conversation_id: The unique id for the conversation. :type conversation_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "from_email": string*, "read": boolean* } """ self.conversation_id = conversation_id if 'from_email' not in data: raise KeyError('The conversation message must have a from_email') check_email(data['from_email']) if 'read' not in data: raise KeyError('The conversation message must have a read') if data['read'] not in [True, False]: raise TypeError('The conversation message read must be True or False') response = self._mc_client._post(url=self._build_path(conversation_id, 'messages'), data=data) if response is not None: self.message_id = response['id'] else: self.message_id = None return response # Paid feature def all(self, conversation_id, **queryparams): """ Get messages from a specific conversation. This endpoint does not currently support count and offset, preventing it from having the get_all parameter that most all() methods have :param conversation_id: The unique id for the conversation. :type conversation_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = p[ queryparams['is_read'] = string queryparams['before_timestamp'] = string queryparams['since_timestamp'] = string """ self.conversation_id = conversation_id self.message_id = None return self._mc_client._get(url=self._build_path(conversation_id, 'messages'), **queryparams) # Paid feature def get(self, conversation_id, message_id, **queryparams): """ Get an individual message in a conversation. :param conversation_id: The unique id for the conversation. :type conversation_id: :py:class:`str` :param message_id: The unique id for the conversation message. :type message_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.conversation_id = conversation_id self.message_id = message_id return self._mc_client._get(url=self._build_path(conversation_id, 'messages', message_id), **queryparams) ================================================ FILE: mailchimp3/entities/conversations.py ================================================ # coding=utf-8 """ The Conversations API endpoint Note: This is a paid feature Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/conversations/ Schema: https://api.mailchimp.com/schema/3.0/Conversations/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.conversationmessages import ConversationMessages class Conversations(BaseApi): """ Conversation tracking is a paid feature that lets you view subscribers’ replies to your campaigns in your MailChimp account. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Conversations, self).__init__(*args, **kwargs) self.endpoint = 'conversations' self.conversation_id = None self.messages = ConversationMessages(self) # Paid feature def all(self, get_all=False, **queryparams): """ Get a list of conversations for the account. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['has_unread_messages'] = string queryparams['list_id'] = string queryparams['campaign_id'] = string """ self.conversation_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) # Paid feature def get(self, conversation_id, **queryparams): """ Get details about an individual conversation. :param conversation_id: The unique id for the conversation. :type conversation_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.conversation_id = conversation_id return self._mc_client._get(url=self._build_path(conversation_id), **queryparams) ================================================ FILE: mailchimp3/entities/customerjourney.py ================================================ # coding=utf-8 """ The Customer Journey API endpoint Documentation: https://mailchimp.com/developer/marketing/api/customer-journeys-journeys-steps-actions/ Schema: https://us1.api.mailchimp.com/schema/3.0/Paths/CustomerJourneys/Journeys/Steps/Actions/Trigger.json """ from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email class CustomerJourney(BaseApi): """ Manage specific customer journeys in your Mailchimp account. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(CustomerJourney, self).__init__(*args, **kwargs) self.endpoint = 'customer-journeys' self.journey_id = None self.step_id = None def trigger(self, journey_id, step_id, data): """ Trigger a step in a customer journey. :param journey_id: The unique id for the Customer Journey :type journey_id: :py:class:`str` :param step_id: The unique id for the step within the customer journey :type step_id: :py:class:`str` :type data: :py:class:`dict` data = { "email": string*, } """ self.journey_id = journey_id self.step_id = step_id if 'email_address' not in data: raise KeyError('The automation email queue must have an email_address') check_email(data['email_address']) response = self._mc_client._post( url=self._build_path("journeys", journey_id, 'steps', step_id, 'actions', "trigger"), data=data ) return response ================================================ FILE: mailchimp3/entities/filemanagerfiles.py ================================================ # coding=utf-8 """ The File Manager Files API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/file-manager/files/ Schema: https://api.mailchimp.com/schema/3.0/FileManager/Files/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class FileManagerFiles(BaseApi): """ Manage specific files in the File Manager for your MailChimp account. The File Manager is a place to store images, documents, and other files you include or link to in your campaigns, templates, or signup forms. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(FileManagerFiles, self).__init__(*args, **kwargs) self.endpoint = 'file-manager/files' self.file_id = None def create(self, data): """ Upload a new image or file to the File Manager. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "file_data": string* } """ if 'name' not in data: raise KeyError('The file must have a name') if 'file_data' not in data: raise KeyError('The file must have file_data') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.file_id = response['id'] else: self.file_id = None return response def all(self, get_all=False, **queryparams): """ Get a list of available images and files stored in the File Manager for the account. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = string queryparams['created_by'] = string queryparams['before_created_at'] = string queryparams['since_created_at'] = string queryparams['sort_field'] = string queryparams['sort_dir'] = string """ self.file_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, file_id, **queryparams): """ Get information about a specific file in the File Manager. :param file_id: The unique id for the File Manager file. :type file_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.file_id = file_id return self._mc_client._get(url=self._build_path(file_id), **queryparams) def update(self, file_id, data): """ Update a file in the File Manager. :param file_id: The unique id for the File Manager file. :type file_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "file_data": string* } """ self.file_id = file_id if 'name' not in data: raise KeyError('The file must have a name') if 'file_data' not in data: raise KeyError('The file must have file_data') return self._mc_client._patch(url=self._build_path(file_id), data=data) def delete(self, file_id): """ Remove a specific file from the File Manager. :param file_id: The unique id for the File Manager file. :type file_id: :py:class:`str` """ self.file_id = file_id return self._mc_client._delete(url=self._build_path(file_id)) ================================================ FILE: mailchimp3/entities/filemanagerfolders.py ================================================ # coding=utf-8 """ The File Manager Folders API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/file-manager/folders/ Schema: https://api.mailchimp.com/schema/3.0/FileManager/Folders/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class FileManagerFolders(BaseApi): """ Manage specific folders in the File Manager for your MailChimp account. The File Manager is a place to store images, documents, and other files you include or link to in your campaigns, templates, or signup forms. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(FileManagerFolders, self).__init__(*args, **kwargs) self.endpoint = 'file-manager/folders' self.folder_id = None def create(self, data): """ Create a new folder in the File Manager. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ if 'name' not in data: raise KeyError('The folder must have a name') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.folder_id = response['id'] else: self.folder_id = None return response def all(self, get_all=False, **queryparams): """ Get a list of all folders in the File Manager. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['created_by'] = string queryparams['before_created_at'] = string queryparams['since_created_at'] = string """ self.folder_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, folder_id, **queryparams): """ Get information about a specific folder in the File Manager. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.folder_id = folder_id return self._mc_client._get(url=self._build_path(folder_id), **queryparams) def update(self, folder_id, data): """ Update a specific File Manager file. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.folder_id = folder_id if 'name' not in data: raise KeyError('The folder must have a name') return self._mc_client._patch(url=self._build_path(folder_id), data=data) def delete(self, folder_id): """ Delete a specific folder in the File Manager. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` """ self.folder_id = folder_id return self._mc_client._delete(url=self._build_path(folder_id)) ================================================ FILE: mailchimp3/entities/landingpageaction.py ================================================ # coding=utf-8 """ The Landinge Page actions API endpoint Documentation: https://mailchimp.com/developer/reference/landing-pages/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class LandingPageAction(BaseApi): """ Manage your Landing Pages, including publishing and unpublishing. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(LandingPageAction, self).__init__(*args, **kwargs) self.endpoint = 'landing-pages' self.page_id = None def publish(self, page_id): """ Publish a landing page that is in draft, unpublished, or has been previously published and edited. :param page_id: The unique id for the page. :type page_id: :py:class:`str` """ self.page_id = page_id return self._mc_client._post(url=self._build_path(page_id, 'actions/publish')) def unpublish(self, page_id): """ Unpublish a landing page that is in draft or has been published. :param page_id: The unique id for the page. :type page_id: :py:class:`str` """ self.page_id = page_id return self._mc_client._post(url=self._build_path(page_id, 'actions/unpublish')) ================================================ FILE: mailchimp3/entities/landingpagecontent.py ================================================ # coding=utf-8 """ The Landing Page Content API endpoint Documentation: https://mailchimp.com/developer/reference/landing-pages/landing-pages_content/ Schema: https://api.mailchimp.com/schema/3.0/Definitions/LandingPages/Content/Response.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class LandingPageContent(BaseApi): """ The HTML content for your Mailchimp landing pages. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(LandingPageContent, self).__init__(*args, **kwargs) self.endpoint = 'landing-pages' self.page_id = None def get(self, page_id, **queryparams): """ Get the the HTML for your landing page. :param page_id: The unique id for the page. :type page_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.page_id = page_id return self._mc_client._get(url=self._build_path(page_id, 'content'), **queryparams) ================================================ FILE: mailchimp3/entities/landingpages.py ================================================ # coding=utf-8 """ The Landing Pages API endpoint Documentation: https://mailchimp.com/developer/reference/landing-pages/ Schema: https://api.mailchimp.com/schema/3.0/LandingPages/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.landingpageaction import LandingPageAction from mailchimp3.entities.landingpagecontent import LandingPageContent class LandingPages(BaseApi): """ Manage your Landing Pages, including publishing and unpublishing. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(LandingPages, self).__init__(*args, **kwargs) self.endpoint = 'landing-pages' self.page_id = None self.content = LandingPageContent(self) self.actions = LandingPageAction(self) def create(self, data): """ Create a new Landing Page. :param data: The request body parameters :type data: :py:class:`dict` data = { "list_id": string*, } """ if 'list_id' not in data: raise KeyError('The landing page must have a list_id') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.page_id = response['id'] else: self.page_id = None return response def all(self, get_all=False, **queryparams): """ Get all landinge pages. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['sort_field'] = string queryparams['sort_dir'] = string queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer """ self.page_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, page_id, **queryparams): """ Get information about a specific page. :param page_id: The unique id for the page. :type page_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.page_id = page_id return self._mc_client._get(url=self._build_path(page_id), **queryparams) def update(self, page_id, data): """ Update a landing page. :param page_id: The unique id for the landing page. :type page_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.page_id = page_id return self._mc_client._patch(url=self._build_path(page_id), data=data) def delete(self, page_id): """ Remove a landing page from your MailChimp account. :param page_id: The unique id for the landing page. :type page_id: :py:class:`str` """ self.page_id = page_id return self._mc_client._delete(url=self._build_path(page_id)) ================================================ FILE: mailchimp3/entities/listabusereports.py ================================================ # coding=utf-8 """ The List Abuse Reports API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/abuse-reports/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Abuse/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListAbuseReports(BaseApi): """ Manage abuse complaints for a specific list. An abuse complaint occurs when your recipient reports an email as spam in their mail program. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListAbuseReports, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.report_id = None def all(self, list_id, get_all=False, **queryparams): """ Get all abuse reports for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.list_id = list_id self.report_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'abuse-reports'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'abuse-reports'), **queryparams) def get(self, list_id, report_id, **queryparams): """ Get details about a specific abuse report. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param report_id: The id for the abuse report. :type report_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.list_id = list_id self.report_id = report_id return self._mc_client._get(url=self._build_path(list_id, 'abuse-reports', report_id), **queryparams) ================================================ FILE: mailchimp3/entities/listactivity.py ================================================ # coding=utf-8 """ The List Activity API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/activity/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Activity/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListActivity(BaseApi): """ Get recent daily, aggregated activity stats for your list. For example, view unsubscribes, signups, total emails sent, opens, clicks, and more, for up to 180 days. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListActivity, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None def all(self, list_id, **queryparams): """ Get up to the previous 180 days of daily detailed aggregated activity stats for a list, not including Automation activity. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id return self._mc_client._get(url=self._build_path(list_id, 'activity'), **queryparams) ================================================ FILE: mailchimp3/entities/listclients.py ================================================ # coding=utf-8 """ The List Clients API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/clients/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Clients/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListClients(BaseApi): """ Get information about the most popular email clients for subscribers in a specific MailChimp list. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListClients, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None def all(self, list_id, **queryparams): """ Get a list of the top email clients based on user-agent strings. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id return self._mc_client._get(url=self._build_path(list_id, 'clients'), **queryparams) ================================================ FILE: mailchimp3/entities/listgrowthhistory.py ================================================ # coding=utf-8 """ The List Growth History API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/growth-history/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Growth/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListGrowthHistory(BaseApi): """ View a summary of the month-by-month growth activity for a specific list. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListGrowthHistory, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.month = None def all(self, list_id, get_all=False, **queryparams): """ Get a month-by-month summary of a specific list’s growth activity. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.list_id = list_id self.month = None if get_all: return self._iterate(url=self._build_path(list_id, 'growth-history'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'growth-history'), **queryparams) def get(self, list_id, month, **queryparams): """ Get a summary of a specific list’s growth activity for a specific month and year. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param month: A specific month of list growth history. :type month: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id self.month = month return self._mc_client._get(url=self._build_path(list_id, 'growth-history', month), **queryparams) ================================================ FILE: mailchimp3/entities/listinterestcategories.py ================================================ # coding=utf-8 """ The List Interest Categories API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/interest-categories/ Schema: https://api.mailchimp.com/schema/3.0/Lists/InterestCategories/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.listinterestcategoryinterest import ListInterestCategoryInterest class ListInterestCategories(BaseApi): """ Manage interest categories for a specific list. Interest categories organize interests, which are used to group subscribers based on their preferences. These correspond to ‘group titles’ in the MailChimp application. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListInterestCategories, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.category_id = None self.interests = ListInterestCategoryInterest(self) def create(self, list_id, data): """ Create a new interest category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "title": string*, "type": string* (Must be one of 'checkboxes', 'dropdown', 'radio', or 'hidden') } """ self.list_id = list_id if 'title' not in data: raise KeyError('The list interest category must have a title') if 'type' not in data: raise KeyError('The list interest category must have a type') if data['type'] not in ['checkboxes', 'dropdown', 'radio', 'hidden']: raise ValueError('The list interest category type must be one of "checkboxes", "dropdown", "radio", or ' '"hidden"') response = self._mc_client._post(url=self._build_path(list_id, 'interest-categories'), data=data) if response is not None: self.category_id = response['id'] else: self.category_id = None return response def all(self, list_id, get_all=False, **queryparams): """ Get information about a list’s interest categories. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = string """ self.list_id = list_id self.category_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'interest-categories'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'interest-categories'), **queryparams) def get(self, list_id, category_id, **queryparams): """ Get information about a specific interest category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id self.category_id = category_id return self._mc_client._get(url=self._build_path(list_id, 'interest-categories', category_id), **queryparams) def update(self, list_id, category_id, data): """ Update a specific interest category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "title": string*, "type": string* (Must be one of 'checkboxes', 'dropdown', 'radio', or 'hidden') } """ self.list_id = list_id self.category_id = category_id if 'title' not in data: raise KeyError('The list interest category must have a title') if 'type' not in data: raise KeyError('The list interest category must have a type') if data['type'] not in ['checkboxes', 'dropdown', 'radio', 'hidden']: raise ValueError('The list interest category type must be one of "checkboxes", "dropdown", "radio", or ' '"hidden"') return self._mc_client._patch(url=self._build_path(list_id, 'interest-categories', category_id), data=data) def delete(self, list_id, category_id): """ Delete a specific interest category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` """ self.list_id = list_id self.category_id = category_id return self._mc_client._delete(url=self._build_path(list_id, 'interest-categories', category_id)) ================================================ FILE: mailchimp3/entities/listinterestcategoryinterest.py ================================================ # coding=utf-8 """ The List Interest Category Interests API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/interest-categories/interests/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Interests/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListInterestCategoryInterest(BaseApi): """ Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListInterestCategoryInterest, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.category_id = None self.interest_id = None def create(self, list_id, category_id, data): """ Create a new interest or ‘group name’ for a specific category. The documentation lists only the name request body parameter so it is being documented and error-checked as if it were required based on the description of the method. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.list_id = list_id self.category_id = category_id if 'name' not in data: raise KeyError('The list interest category interest must have a name') response = self._mc_client._post( url=self._build_path(list_id, 'interest-categories', category_id, 'interests'), data=data ) if response is not None: self.interest_id = response['id'] else: self.interest_id = None return response def all(self, list_id, category_id, get_all=False, **queryparams): """ Get a list of this category’s interests. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.list_id = list_id self.category_id = category_id self.interest_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'interest-categories', category_id, 'interests'), **queryparams) else: return self._mc_client._get( url=self._build_path(list_id, 'interest-categories', category_id, 'interests'), **queryparams ) def get(self, list_id, category_id, interest_id, **queryparams): """ Get interests or ‘group names’ for a specific category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param interest_id: The specific interest or ‘group name’. :type interest_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id self.category_id = category_id self.interest_id = interest_id return self._mc_client._get( url=self._build_path(list_id, 'interest-categories', category_id, 'interests', interest_id), **queryparams ) def update(self, list_id, category_id, interest_id, data): """ Update interests or ‘group names’ for a specific category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param interest_id: The specific interest or ‘group name’. :type interest_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.list_id = list_id self.category_id = category_id self.interest_id = interest_id if 'name' not in data: raise KeyError('The list interest category interest must have a name') return self._mc_client._patch( url=self._build_path(list_id, 'interest-categories', category_id, 'interests', interest_id), data=data ) def delete(self, list_id, category_id, interest_id): """ Delete interests or group names in a specific category. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param category_id: The unique id for the interest category. :type category_id: :py:class:`str` :param interest_id: The specific interest or ‘group name’. :type interest_id: :py:class:`str` """ self.list_id = list_id self.category_id = category_id self.interest_id = interest_id return self._mc_client._delete( url=self._build_path(list_id, 'interest-categories', category_id, 'interests', interest_id) ) ================================================ FILE: mailchimp3/entities/listmemberactivity.py ================================================ # coding=utf-8 """ The List Member Activity API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/activity/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Activity/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ListMemberActivity(BaseApi): """ Get details about subscribers’ recent activity. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMemberActivity, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None def all(self, list_id, subscriber_hash, **queryparams): """ Get the last 50 events of a member’s activity on a specific list, including opens, clicks, and unsubscribes. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'activity'), **queryparams) def feed(self, list_id, subscriber_hash, **queryparams): """ Get the last 10 events of a member’s activity on a specific list, including opens, clicks, and unsubscribes. With count parameter, get as many past events as you would like. Returns many more fields not accessible by all endpoint. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'activity-feed'), **queryparams) ================================================ FILE: mailchimp3/entities/listmemberevents.py ================================================ # coding=utf-8 """ The List Member Events API endpoint Documentation: https://mailchimp.com/developer/reference/lists/list-members/list-member-events/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ListMemberEvents(BaseApi): """ Use the Events endpoint to collect website or in-app actions and trigger targeted automations. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMemberEvents, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None def create(self, list_id, subscriber_hash, data): """ Add an event for a list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, (Must be 2-30 characters in length) } """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash if 'name' not in data: raise KeyError('The list member events must have a name') if len(data['name']) < 2 or len(data['name']) > 30: raise ValueError('The list member events name must be 2-30 in length') return self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'events'), data=data) def all(self, list_id, subscriber_hash, get_all=False, **queryparams): """ Get events for a contact :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['count'] = integer queryparams['offset'] = integer queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash if get_all: return self._iterate(url=self._build_path(list_id, 'members', subscriber_hash, 'events'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'events'), **queryparams) ================================================ FILE: mailchimp3/entities/listmembergoals.py ================================================ # coding=utf-8 """ The List Member Goals API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/goals/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Goals/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ListMemberGoals(BaseApi): """ Get information about recent goal events for a specific list member. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMemberGoals, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None def all(self, list_id, subscriber_hash, **queryparams): """ Get the last 50 Goal events for a member on a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'goals'), **queryparams) ================================================ FILE: mailchimp3/entities/listmembernotes.py ================================================ # coding=utf-8 """ The List Member Notes API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/notes/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Notes/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ListMemberNotes(BaseApi): """ Retrieve recent notes for a specific list member. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMemberNotes, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None self.note_id = None def create(self, list_id, subscriber_hash, data): """ Add a new note for a specific subscriber. The documentation lists only the note request body parameter so it is being documented and error-checked as if it were required based on the description of the method. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "note": string* } """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash if 'note' not in data: raise KeyError('The list member note must have a note') response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'notes'), data=data) if response is not None: self.note_id = response['id'] else: self.note_id = None return response def all(self, list_id, subscriber_hash, get_all=False, **queryparams): """ Get recent notes for a specific list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash self.note_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'members', subscriber_hash, 'notes'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'notes'), **queryparams) def get(self, list_id, subscriber_hash, note_id, **queryparams): """ Get a specific note for a specific list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param note_id: The id for the note. :type note_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash self.note_id = note_id return self._mc_client._get( url=self._build_path(list_id, 'members', subscriber_hash, 'notes', note_id), **queryparams ) def update(self, list_id, subscriber_hash, note_id, data): """ Update a specific note for a specific list member. The documentation lists only the note request body parameter so it is being documented and error-checked as if it were required based on the description of the method. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param note_id: The id for the note. :type note_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "note": string* } """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash self.note_id = note_id if 'note' not in data: raise KeyError('The list member note must have a note') return self._mc_client._patch( url=self._build_path(list_id, 'members', subscriber_hash, 'notes', note_id), data=data ) def delete(self, list_id, subscriber_hash, note_id): """ Delete a specific note for a specific list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param note_id: The id for the note. :type note_id: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash self.note_id = note_id return self._mc_client._delete(url=self._build_path(list_id, 'members', subscriber_hash, 'notes', note_id)) ================================================ FILE: mailchimp3/entities/listmembers.py ================================================ # coding=utf-8 """ The List Members API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.listmemberactivity import ListMemberActivity from mailchimp3.entities.listmemberevents import ListMemberEvents from mailchimp3.entities.listmembergoals import ListMemberGoals from mailchimp3.entities.listmembernotes import ListMemberNotes from mailchimp3.helpers import check_email, check_subscriber_hash class ListMembers(BaseApi): """ Manage members of a specific MailChimp list, including currently subscribed, unsubscribed, and bounced members. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMembers, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None self.activity = ListMemberActivity(self) self.events = ListMemberEvents(self) self.goals = ListMemberGoals(self) self.notes = ListMemberNotes(self) def create(self, list_id, data): """ Add a new member to the list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "status": string*, (Must be one of 'subscribed', 'unsubscribed', 'cleaned', 'pending', or 'transactional') "email_address": string* } """ self.list_id = list_id if 'status' not in data: raise KeyError('The list member must have a status') if data['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']: raise ValueError('The list member status must be one of "subscribed", "unsubscribed", "cleaned", ' '"pending", or "transactional"') if 'email_address' not in data: raise KeyError('The list member must have an email_address') check_email(data['email_address']) response = self._mc_client._post(url=self._build_path(list_id, 'members'), data=data) if response is not None: self.subscriber_hash = response['id'] else: self.subscriber_hash = None return response def all(self, list_id, get_all=False, **queryparams): """ Get information about members in a specific MailChimp list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['email_type'] = string queryparams['status'] = string queryparams['before_timestamp_opt'] = string queryparams['since_timestamp_opt'] = string queryparams['before_last_changed'] = string queryparams['since_last_changed'] = string queryparams['unique_email_id'] = string queryparams['vip_only'] = boolean queryparams['interest_category_id'] = string queryparams['interest_ids'] = string queryparams['interest_match'] = string """ self.list_id = list_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(list_id, 'members'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'members'), **queryparams) def get(self, list_id, subscriber_hash, **queryparams): """ Get information about a specific list member, including a currently subscribed, unsubscribed, or bounced member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash), **queryparams) def update(self, list_id, subscriber_hash, data): """ Update information for a specific list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._patch(url=self._build_path(list_id, 'members', subscriber_hash), data=data) def create_or_update(self, list_id, subscriber_hash, data): """ Add or update a list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string*, "status_if_new": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', 'pending', or 'transactional') } """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash if 'email_address' not in data: raise KeyError('The list member must have an email_address') check_email(data['email_address']) if 'status_if_new' not in data: raise KeyError('The list member must have a status_if_new') if data['status_if_new'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']: raise ValueError('The list member status_if_new must be one of "subscribed", "unsubscribed", "cleaned", ' '"pending", or "transactional"') return self._mc_client._put(url=self._build_path(list_id, 'members', subscriber_hash), data=data) def delete(self, list_id, subscriber_hash): """ Delete a member from a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._delete(url=self._build_path(list_id, 'members', subscriber_hash)) def delete_permanent(self, list_id, subscriber_hash): """ Delete permanently a member from a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'actions', 'delete-permanent')) ================================================ FILE: mailchimp3/entities/listmembertags.py ================================================ # coding=utf-8 """ The List Member Tags API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/tags/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Tags/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ListMemberTags(BaseApi): """ Retrieve tags for a specific list member. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMemberTags, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.subscriber_hash = None def update(self, list_id, subscriber_hash, data): """ Update tags for a specific subscriber. The documentation lists only the tags request body parameter so it is being documented and error-checked as if it were required based on the description of the method. The data list needs to include a "status" key. This determines if the tag should be added or removed from the user: data = { 'tags': [ {'name': 'foo', 'status': 'active'}, {'name': 'bar', 'status': 'inactive'} ] } :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "tags": list* } """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash if 'tags' not in data: raise KeyError('The list member tags must have a tag') response = self._mc_client._post(url=self._build_path(list_id, 'members', subscriber_hash, 'tags'), data=data) return response def all(self, list_id, subscriber_hash, **queryparams): """ Get all tags for a specific list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash, 'tags'), **queryparams) ================================================ FILE: mailchimp3/entities/listmergefields.py ================================================ # coding=utf-8 """ The List Merge Fields API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/merge-fields/ Schema: https://api.mailchimp.com/schema/3.0/Lists/MergeFields/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListMergeFields(BaseApi): """ Manage merge fields (formerly merge vars) for a specific list. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListMergeFields, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.merge_id = None def create(self, list_id, data): """ Add a new merge field for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "type": string* } """ self.list_id = list_id if 'name' not in data: raise KeyError('The list merge field must have a name') if 'type' not in data: raise KeyError('The list merge field must have a type') response = self._mc_client._post(url=self._build_path(list_id, 'merge-fields'), data=data) if response is not None: self.merge_id = response['merge_id'] else: self.merge_id = None return response def all(self, list_id, get_all=False, **queryparams): """ Get a list of all merge fields (formerly merge vars) for a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = string queryparams['required'] = boolean """ self.list_id = list_id self.merge_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'merge-fields'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'merge-fields'), **queryparams) def get(self, list_id, merge_id): """ Get information about a specific merge field in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param merge_id: The id for the merge field. :type merge_id: :py:class:`str` """ self.list_id = list_id self.merge_id = merge_id return self._mc_client._get(url=self._build_path(list_id, 'merge-fields', merge_id)) def update(self, list_id, merge_id, data): """ Update a specific merge field in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param merge_id: The id for the merge field. :type merge_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.list_id = list_id self.merge_id = merge_id if 'name' not in data: raise KeyError('The list merge field must have a name') return self._mc_client._patch(url=self._build_path(list_id, 'merge-fields', merge_id), data=data) def delete(self, list_id, merge_id): """ Delete a specific merge field in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param merge_id: The id for the merge field. :type merge_id: :py:class:`str` """ self.list_id = list_id self.merge_id = merge_id return self._mc_client._delete(url=self._build_path(list_id, 'merge-fields', merge_id)) ================================================ FILE: mailchimp3/entities/lists.py ================================================ # coding=utf-8 """ The Lists API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.listabusereports import ListAbuseReports from mailchimp3.entities.listactivity import ListActivity from mailchimp3.entities.listclients import ListClients from mailchimp3.entities.listgrowthhistory import ListGrowthHistory from mailchimp3.entities.listinterestcategories import ListInterestCategories from mailchimp3.entities.listmembers import ListMembers from mailchimp3.entities.listmergefields import ListMergeFields from mailchimp3.entities.listsegments import ListSegments from mailchimp3.entities.listsignupforms import ListSignupForms from mailchimp3.entities.listwebhooks import ListWebhooks from mailchimp3.helpers import check_email class Lists(BaseApi): """ A MailChimp list is a powerful and flexible tool that helps you manage your contacts. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Lists, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.abuse_reports = ListAbuseReports(self) self.activity = ListActivity(self) self.clients = ListClients(self) self.growth_history = ListGrowthHistory(self) self.interest_categories = ListInterestCategories(self) self.members = ListMembers(self) self.merge_fields = ListMergeFields(self) self.segments = ListSegments(self) self.signup_forms = ListSignupForms(self) self.webhooks = ListWebhooks(self) def create(self, data): """ Create a new list in your MailChimp account. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "contact": object* { "company": string*, "address1": string*, "city": string*, "state": string*, "zip": string*, "country": string* }, "permission_reminder": string*, "campaign_defaults": object* { "from_name": string*, "from_email": string*, "subject": string*, "language": string* }, "email_type_option": boolean } """ if 'name' not in data: raise KeyError('The list must have a name') if 'contact' not in data: raise KeyError('The list must have a contact') if 'company' not in data['contact']: raise KeyError('The list contact must have a company') if 'address1' not in data['contact']: raise KeyError('The list contact must have a address1') if 'city' not in data['contact']: raise KeyError('The list contact must have a city') if 'state' not in data['contact']: raise KeyError('The list contact must have a state') if 'zip' not in data['contact']: raise KeyError('The list contact must have a zip') if 'country' not in data['contact']: raise KeyError('The list contact must have a country') if 'permission_reminder' not in data: raise KeyError('The list must have a permission_reminder') if 'campaign_defaults' not in data: raise KeyError('The list must have a campaign_defaults') if 'from_name' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a from_name') if 'from_email' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a from_email') check_email(data['campaign_defaults']['from_email']) if 'subject' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a subject') if 'language' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a language') if 'email_type_option' not in data: raise KeyError('The list must have an email_type_option') if data['email_type_option'] not in [True, False]: raise TypeError('The list email_type_option must be True or False') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.list_id = response['id'] else: self.list_id = None return response def update_members(self, list_id, data): """ Batch subscribe or unsubscribe list members. Only the members array is required in the request body parameters. Within the members array, each member requires an email_address and either a status or status_if_new. The update_existing parameter will also be considered required to help prevent accidental updates to existing members and will default to false if not present. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "members": array* [ { "email_address": string*, "status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'), "status_if_new": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending') } ], "update_existing": boolean* } """ self.list_id = list_id if 'members' not in data: raise KeyError('The update must have at least one member') else: if not len(data['members']) <= 500: raise ValueError('You may only batch sub/unsub 500 members at a time') for member in data['members']: if 'email_address' not in member: raise KeyError('Each list member must have an email_address') check_email(member['email_address']) if 'status' not in member and 'status_if_new' not in member: raise KeyError('Each list member must have either a status or a status_if_new') valid_statuses = ['subscribed', 'unsubscribed', 'cleaned', 'pending'] if 'status' in member and member['status'] not in valid_statuses: raise ValueError('The list member status must be one of "subscribed", "unsubscribed", "cleaned", or ' '"pending"') if 'status_if_new' in member and member['status_if_new'] not in valid_statuses: raise ValueError('The list member status_if_new must be one of "subscribed", "unsubscribed", ' '"cleaned", or "pending"') if 'update_existing' not in data: data['update_existing'] = False return self._mc_client._post(url=self._build_path(list_id), data=data) def all(self, get_all=False, **queryparams): """ Get information about all lists in the account. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['before_date_created'] = string queryparams['since_date_created'] = string queryparams['before_campaign_last_sent'] = string queryparams['since_campaign_last_sent'] = string queryparams['email'] = string queryparams['sort_field'] = string (Must be 'date_created') queryparams['sort_dir'] = string (Must be one of 'ASC' or 'DESC') """ self.list_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, list_id, **queryparams): """ Get information about a specific list in your MailChimp account. Results include list members who have signed up but haven’t confirmed their subscription yet and unsubscribed or cleaned. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id return self._mc_client._get(url=self._build_path(list_id), **queryparams) def update(self, list_id, data): """ Update the settings for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "contact": object* { "company": string*, "address1": string*, "city": string*, "state": string*, "zip": string*, "country": string* }, "permission_reminder": string*, "campaign_defaults": object* { "from_name": string*, "from_email": string*, "subject": string*, "language": string* }, "email_type_option": boolean } """ self.list_id = list_id if 'name' not in data: raise KeyError('The list must have a name') if 'contact' not in data: raise KeyError('The list must have a contact') if 'company' not in data['contact']: raise KeyError('The list contact must have a company') if 'address1' not in data['contact']: raise KeyError('The list contact must have a address1') if 'city' not in data['contact']: raise KeyError('The list contact must have a city') if 'state' not in data['contact']: raise KeyError('The list contact must have a state') if 'zip' not in data['contact']: raise KeyError('The list contact must have a zip') if 'country' not in data['contact']: raise KeyError('The list contact must have a country') if 'permission_reminder' not in data: raise KeyError('The list must have a permission_reminder') if 'campaign_defaults' not in data: raise KeyError('The list must have a campaign_defaults') if 'from_name' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a from_name') if 'from_email' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a from_email') check_email(data['campaign_defaults']['from_email']) if 'subject' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a subject') if 'language' not in data['campaign_defaults']: raise KeyError('The list campaign_defaults must have a language') if 'email_type_option' not in data: raise KeyError('The list must have an email_type_option') if data['email_type_option'] not in [True, False]: raise TypeError('The list email_type_option must be True or False') return self._mc_client._patch(url=self._build_path(list_id), data=data) def delete(self, list_id): """ Delete a list from your MailChimp account. If you delete a list, you’ll lose the list history—including subscriber activity, unsubscribes, complaints, and bounces. You’ll also lose subscribers’ email addresses, unless you exported and backed up your list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` """ self.list_id = list_id return self._mc_client._delete(url=self._build_path(list_id)) ================================================ FILE: mailchimp3/entities/listsegmentmembers.py ================================================ # coding=utf-8 """ The List Segment Members API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/members/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email, check_subscriber_hash class ListSegmentMembers(BaseApi): """ Manage list members in a saved segment. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListSegmentMembers, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.segment_id = None self.subscriber_hash = None def create(self, list_id, segment_id, data): """ Add a member to a static segment. The documentation does not currently elaborate on the path or request body parameters. Looking at the example provided, it will be assumed that email_address and status are required request body parameters and they are documented and error-checked as such. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "email_address": string*, "status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending') } """ self.list_id = list_id self.segment_id = segment_id if 'email_address' not in data: raise KeyError('The list segment member must have an email_address') check_email(data['email_address']) if 'status' not in data: raise KeyError('The list segment member must have a status') if data['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending']: raise ValueError('The list segment member status must be one of "subscribed", "unsubscribed", "cleaned" or' '"pending"') response = self._mc_client._post(url=self._build_path(list_id, 'segments', segment_id, 'members'), data=data) if response is not None: self.subscriber_hash = response['id'] else: self.subscriber_hash = None return response def all(self, list_id, segment_id, get_all=False, **queryparams): """ Get information about members in a saved segment. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.list_id = list_id self.segment_id = segment_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(list_id, 'segments', segment_id, 'members'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id, 'members'), **queryparams) def delete(self, list_id, segment_id, subscriber_hash): """ Remove a member from the specified static segment. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.list_id = list_id self.segment_id = segment_id self.subscriber_hash = subscriber_hash return self._mc_client._delete( url=self._build_path(list_id, 'segments', segment_id, 'members', subscriber_hash) ) ================================================ FILE: mailchimp3/entities/listsegments.py ================================================ # coding=utf-8 """ The List Segments API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Segments/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.listsegmentmembers import ListSegmentMembers class ListSegments(BaseApi): """ Manage segments for a specific MailChimp list. A segment is a section of your list that includes only those subscribers who share specific common field information. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListSegments, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.segment_id = None self.members = ListSegmentMembers(self) def create(self, list_id, data): """ Create a new segment in a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.list_id = list_id if 'name' not in data: raise KeyError('The list segment must have a name') response = self._mc_client._post(url=self._build_path(list_id, 'segments'), data=data) if response is not None: self.segment_id = response['id'] else: self.segment_id = None return response def all(self, list_id, get_all=False, **queryparams): """ Get information about all available segments for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = string queryparams['before_created_at'] = string queryparams['since_created_at'] = string queryparams['before_updated_at'] = string queryparams['since_updated_at'] = string """ self.list_id = list_id self.segment_id = None if get_all: return self._iterate(url=self._build_path(list_id, 'segments'), **queryparams) else: return self._mc_client._get(url=self._build_path(list_id, 'segments'), **queryparams) def get(self, list_id, segment_id, **queryparams): """ Get information about a specific segment. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.list_id = list_id self.segment_id = segment_id return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id), **queryparams) def update(self, list_id, segment_id, data): """ Update a specific segment in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ self.list_id = list_id self.segment_id = segment_id if 'name' not in data: raise KeyError('The list segment must have a name') return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data) def update_members(self, list_id, segment_id, data): """ Batch add/remove list members to static segment. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "members_to_add": array, "members_to_remove": array } """ self.list_id = list_id self.segment_id = segment_id return self._mc_client._post(url=self._build_path(list_id, 'segments', segment_id), data=data) def delete(self, list_id, segment_id): """ Delete a specific segment in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param segment_id: The unique id for the segment. :type segment_id: :py:class:`str` """ self.list_id = list_id self.segment_id = segment_id return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id)) ================================================ FILE: mailchimp3/entities/listsignupforms.py ================================================ # coding=utf-8 """ The List Signup Forms API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/signup-forms/ Schema: https://api.mailchimp.com/schema/3.0/Lists/SignupForms/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ListSignupForms(BaseApi): """ Manage list signup forms. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListSignupForms, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None def create(self, list_id, data): """ Create a customized list signup form. No fields are listed as required in the documentation and the description of the method does not indicate any required fields either. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.list_id = list_id response = self._mc_client._post(url=self._build_path(list_id, 'signup-forms'), data=data) return response def all(self, list_id): """ Get signup forms for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` """ self.list_id = list_id return self._mc_client._get(url=self._build_path(list_id, 'signup-forms')) ================================================ FILE: mailchimp3/entities/listwebhooks.py ================================================ # coding=utf-8 """ The List Webhooks API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/webhooks/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Webhooks/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_url class ListWebhooks(BaseApi): """ Manage webhooks for a specific MailChimp list. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListWebhooks, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.webhook_id = None def create(self, list_id, data): """ Create a new webhook for a specific list. The documentation does not include any required request body parameters but the url parameter is being listed here as a required parameter in documentation and error-checking based on the description of the method :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "url": string* } """ self.list_id = list_id if 'url' not in data: raise KeyError('The list webhook must have a url') check_url(data['url']) response = self._mc_client._post(url=self._build_path(list_id, 'webhooks'), data=data) if response is not None: self.webhook_id = response['id'] else: self.webhook_id = None return response def all(self, list_id): """ Get information about all webhooks for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = None return self._mc_client._get(url=self._build_path(list_id, 'webhooks')) def get(self, list_id, webhook_id): """ Get information about a specific webhook. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook. :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._get(url=self._build_path(list_id, 'webhooks', webhook_id)) def update(self, list_id, webhook_id, data): """ Update the settings for an existing webhook. :param list_id: The unique id for the list :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._patch(url=self._build_path(list_id, 'webhooks', webhook_id), data=data) def delete(self, list_id, webhook_id): """ Delete a specific webhook in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook. :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._delete(url=self._build_path(list_id, 'webhooks', webhook_id)) ================================================ FILE: mailchimp3/entities/ping.py ================================================ # coding=utf-8 """ The Google Analytics API Endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ping """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class Ping(BaseApi): """ A health check endpoint for MailChimp API 3.0. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Ping, self).__init__(*args, **kwargs) self.endpoint = 'ping' def get(self): """ A health check for the API that won’t return any account-specific information. """ return self._mc_client._get(url=self._build_path()) ================================================ FILE: mailchimp3/entities/reportcampaignabusereports.py ================================================ # coding=utf-8 """ The Campaign Abuse Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/abuse-reports/ """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportCampaignAbuseReports(BaseApi): """ Get information about campaign abuse complaints. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.report_id = None def all(self, campaign_id, **queryparams): """ Get a list of abuse complaints for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.report_id = None return self._mc_client._get(url=self._build_path(campaign_id, 'abuse-reports'), **queryparams) def get(self, campaign_id, report_id, **queryparams): """ Get information about a specific abuse report for a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param report_id: The id for the abuse report. :type report_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.report_id = report_id return self._mc_client._get(url=self._build_path(campaign_id, 'abuse-reports', report_id), **queryparams) ================================================ FILE: mailchimp3/entities/reportcampaignadvice.py ================================================ # coding=utf-8 """ The Campaign Advice Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/advice/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Advice/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportCampaignAdvice(BaseApi): """ Get recent feedback based on a campaign’s statistics. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportCampaignAdvice, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, **queryparams): """ Get feedback based on a campaign’s statistics. Advice feedback is based on campaign stats like opens, clicks, unsubscribes, bounces, and more. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'advice'), **queryparams) ================================================ FILE: mailchimp3/entities/reportclickdetailmembers.py ================================================ # coding=utf-8 """ The Click Detail Report Members API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/click-details/members/ Schema: https://api.mailchimp.com/schema/3.0/Reports/ClickDetails/Members/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ReportClickDetailMembers(BaseApi): """ Get information about specific subscribers who clicked on links in a campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportClickDetailMembers, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.link_id = None self.subscriber_hash = None def all(self, campaign_id, link_id, get_all=False, **queryparams): """ Get information about list members who clicked on a specific link in a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param link_id: The id for the link. :type link_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id self.link_id = link_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'click-details', link_id, 'members'), **queryparams) else: return self._mc_client._get( url=self._build_path(campaign_id, 'click-details', link_id, 'members'), **queryparams ) def get(self, campaign_id, link_id, subscriber_hash, **queryparams): """ Get information about a specific subscriber who clicked a link in a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param link_id: The id for the link. :type link_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.campaign_id = campaign_id self.link_id = link_id self.subscriber_hash = subscriber_hash return self._mc_client._get( url=self._build_path(campaign_id, 'click-details', link_id, 'members', subscriber_hash), **queryparams ) ================================================ FILE: mailchimp3/entities/reportclickdetailreports.py ================================================ # coding=utf-8 """ The Click Details Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/click-details/ Schema: https://api.mailchimp.com/schema/3.0/Reports/ClickDetails/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.reportclickdetailmembers import ReportClickDetailMembers class ReportClickDetailReports(BaseApi): """ Get detailed information about links clicked in campaigns. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportClickDetailReports, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.link_id = None self.members = ReportClickDetailMembers(self) def all(self, campaign_id, get_all=False, **queryparams): """ Get information about clicks on specific links in your MailChimp campaigns. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id self.link_id = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'click-details'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'click-details'), **queryparams) def get(self, campaign_id, link_id, **queryparams): """ Get click details for a specific link in a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param link_id: The id for the link. :type link_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.link_id = link_id return self._mc_client._get(url=self._build_path(campaign_id, 'click-details', link_id), **queryparams) ================================================ FILE: mailchimp3/entities/reportdomainperformance.py ================================================ # coding=utf-8 """ The Domain Performance Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/domain-performance/ Schema: https://api.mailchimp.com/schema/3.0/Reports/DomainPerformance/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportDomainPerformance(BaseApi): """ Get statistics for the top-performing domains from a campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportDomainPerformance, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, **queryparams): """ Get statistics for the top-performing email domains in a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'domain-performance'), **queryparams) ================================================ FILE: mailchimp3/entities/reporteepurl.py ================================================ # coding=utf-8 """ The EepURL Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/eepurl/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Eepurl/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportEepURL(BaseApi): """ Get a summary of social activity for the campaign, tracked by EepURL. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportEepURL, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, **queryparams): """ Get a summary of social activity for the campaign, tracked by EepURL. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'eepurl'), **queryparams) ================================================ FILE: mailchimp3/entities/reportemailactivity.py ================================================ # coding=utf-8 """ The Email Activity Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/email-activity/ Schema: https://api.mailchimp.com/schema/3.0/Reports/EmailActivity/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ReportEmailActivity(BaseApi): """ Get list member activity for a specific campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportEmailActivity, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.subscriber_hash = None def all(self, campaign_id, get_all=False, **queryparams): """ Get a list of member’s subscriber activity in a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'email-activity'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'email-activity'), **queryparams) def get(self, campaign_id, subscriber_hash, **queryparams): """ Get a specific list member’s activity in a campaign including opens, clicks, and bounces. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.campaign_id = campaign_id self.subscriber_hash = subscriber_hash return self._mc_client._get( url=self._build_path(campaign_id, 'email-activity', subscriber_hash), **queryparams ) ================================================ FILE: mailchimp3/entities/reportgoogleanalytics.py ================================================ # coding=utf-8 """ The Google Analytics API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/google-analytics/ Schema: https://api.mailchimp.com/schema/3.0/Reports/GoogleAnalytics/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportGoogleAnalytics(BaseApi): """ Get top open locations for a specific campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportGoogleAnalytics, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.profile_id = None def all(self, campaign_id, get_all=False, **queryparams): """ Get a summary of Google Analytics reports for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id if get_all: return self._iterate(url=self._build_path(campaign_id, 'google-analytics'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'google-analytics'), **queryparams) def get(self, campaign_id, profile_id, **queryparams): """ Get information about a specific Google Analytics report for a campaign. :param campaign_id: The unique id for the campaign :type campaign_id: :py:class:`str` :param profile_id: The Google Analytics View ID :type campaign_id: :py:class:`str` :param queryparams: :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id self.profile_id = profile_id return self._mc_client._get(url=self._build_path(campaign_id, 'google-analytics', profile_id), **queryparams) ================================================ FILE: mailchimp3/entities/reportlocations.py ================================================ # coding=utf-8 """ The Location Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/locations/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Locations/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportLocations(BaseApi): """ Get top open locations for a specific campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportLocations, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, get_all=False, **queryparams): """ Get top open locations for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id if get_all: return self._iterate(url=self._build_path(campaign_id, 'locations'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'locations'), **queryparams) ================================================ FILE: mailchimp3/entities/reportopendetails.py ================================================ # coding=utf-8 """ The Location Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/open-details/ Schema: https://api.mailchimp.com/schema/3.0/Reports/OpenDetails/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class OpenDetails(BaseApi): """ Get a detailed report about any emails in a specific campaign that were opened by the recipient. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(OpenDetails, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, get_all=False, **queryparams): """ Get detailed information about any campaign emails that were opened by a list member. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['since'] = str """ self.campaign_id = campaign_id if get_all: return self._iterate(url=self._build_path(campaign_id, 'open-details'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'open-details'), **queryparams) class ReportOpenDetails(OpenDetails): """ Clone OpenDetails class as ReportOpenDetails for naming consistency """ pass ================================================ FILE: mailchimp3/entities/reports.py ================================================ # coding=utf-8 """ The Reports API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.reportcampaignabusereports import ReportCampaignAbuseReports from mailchimp3.entities.reportcampaignadvice import ReportCampaignAdvice from mailchimp3.entities.reportclickdetailreports import ReportClickDetailReports from mailchimp3.entities.reportdomainperformance import ReportDomainPerformance from mailchimp3.entities.reporteepurl import ReportEepURL from mailchimp3.entities.reportemailactivity import ReportEmailActivity from mailchimp3.entities.reportlocations import ReportLocations from mailchimp3.entities.reportsentto import ReportSentTo from mailchimp3.entities.reportsubreports import ReportSubReports from mailchimp3.entities.reportunsubscribes import ReportUnsubscribes class Reports(BaseApi): """ Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Reports, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.abuse_reports = ReportCampaignAbuseReports(self) self.advice = ReportCampaignAdvice(self) self.click_details = ReportClickDetailReports(self) self.domain_performance = ReportDomainPerformance(self) self.eepurl = ReportEepURL(self) self.email_activity = ReportEmailActivity(self) self.locations = ReportLocations(self) self.sent_to = ReportSentTo(self) self.subreports = ReportSubReports(self) self.unsubscribes = ReportUnsubscribes(self) def all(self, get_all=False, **queryparams): """ Get campaign reports. .. note:: The before_send_time and since_send_time queryparams expect times to be listed in the ISO 8601 format in UTC (ex. 2015-10-21T15:41:36+00:00). :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['type'] = [] queryparams['before_send_time'] = string queryparams['since_send_time'] = string """ self.campaign_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, campaign_id, **queryparams): """ Get report details for a specific sent campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id), **queryparams) ================================================ FILE: mailchimp3/entities/reportsentto.py ================================================ # coding=utf-8 """ The Sent To Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/sent-to/ Schema: https://api.mailchimp.com/schema/3.0/Reports/SentTo/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ReportSentTo(BaseApi): """ Get details about campaign recipients. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportSentTo, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.subscriber_hash = None def all(self, campaign_id, get_all=False, **queryparams): """ Get information about campaign recipients. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'sent-to'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'sent-to'), **queryparams) def get(self, campaign_id, subscriber_hash, **queryparams): """ Get information about a specific campaign recipient. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.campaign_id = campaign_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(campaign_id, 'sent-to', subscriber_hash), **queryparams) ================================================ FILE: mailchimp3/entities/reportsubreports.py ================================================ # coding=utf-8 """ The Sub-Reports Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/sub-reports/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Sub/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class ReportSubReports(BaseApi): """ A list of reports for child campaigns of a specific parent campaign. For example, use this endpoint to view Multivariate, RSS, and A/B Testing Campaign reports. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ReportSubReports, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None def all(self, campaign_id, **queryparams): """ Get a list of reports with child campaigns for a specific parent campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.campaign_id = campaign_id return self._mc_client._get(url=self._build_path(campaign_id, 'sub-reports'), **queryparams) ================================================ FILE: mailchimp3/entities/reportunsubscribes.py ================================================ # coding=utf-8 """ The Unsubscribes Report API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/reports/unsubscribed/ Schema: https://api.mailchimp.com/schema/3.0/Reports/Unsubs/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_subscriber_hash class ReportUnsubscribes(BaseApi): """ Get information about list members who unsubscribed from a specific campaign. """ def __init__(self, *args, **kwargs): super(ReportUnsubscribes, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None self.subscriber_hash = None def all(self, campaign_id, get_all=False, **queryparams): """ Get information about members who have unsubscribed from a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.campaign_id = campaign_id self.subscriber_hash = None if get_all: return self._iterate(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams) else: return self._mc_client._get(url=self._build_path(campaign_id, 'unsubscribed'), **queryparams) def get(self, campaign_id, subscriber_hash, **queryparams): """ Get information about a specific list member who unsubscribed from a campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase version of the list member’s email address. :type subscriber_hash: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ subscriber_hash = check_subscriber_hash(subscriber_hash) self.campaign_id = campaign_id self.subscriber_hash = subscriber_hash return self._mc_client._get(url=self._build_path(campaign_id, 'unsubscribed', subscriber_hash), **queryparams) ================================================ FILE: mailchimp3/entities/root.py ================================================ # coding=utf-8 """ The API Root endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/root/ Schema: https://api.mailchimp.com/schema/3.0/Root.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class Root(BaseApi): """ The API root resource links to all other resources available in the API. Calling the root directory also returns details about the MailChimp user account. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Root, self).__init__(*args, **kwargs) self.endpoint = '' def get(self, **queryparams): """ Get links to all other resources available in the API. :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ return self._mc_client._get(url=self._build_path(), **queryparams) ================================================ FILE: mailchimp3/entities/searchcampaigns.py ================================================ # coding=utf-8 """ The Search Members API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/search-campaigns/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Collection.json Additional Data: http://kb.mailchimp.com/accounts/management/search-for-subscribers-and-campaigns-in-your-account """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class SearchCampaigns(BaseApi): """ Search all of an account’s campaigns for the specified query terms. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(SearchCampaigns, self).__init__(*args, **kwargs) self.endpoint = 'search-campaigns' def get(self, **queryparams): """ Search all campaigns for the specified query terms. :param queryparams: The query string parameters queryparams['fields'] = array queryparams['exclude_fields'] = array queryparams['query'] = string queryparams['snip_start'] = string queryparams['snip_end'] = string queryparams['offset'] = integer """ return self._mc_client._get(url=self._build_path(), **queryparams) ================================================ FILE: mailchimp3/entities/searchmembers.py ================================================ # coding=utf-8 """ The Search Members API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/search-members/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Collection.json Additional Data: http://kb.mailchimp.com/accounts/management/search-for-subscribers-and-campaigns-in-your-account """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class SearchMembers(BaseApi): """ Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(SearchMembers, self).__init__(*args, **kwargs) self.endpoint = 'search-members' self.list_id = None def get(self, **queryparams): """ Search for list members. This search can be restricted to a specific list, or can be used to search across all lists in an account. :param queryparams: The query string parameters queryparams['fields'] = array queryparams['exclude_fields'] = array queryparams['query'] = string queryparams['list_id'] = string queryparams['offset'] = integer """ if 'list_id' in queryparams: self.list_id = queryparams['list_id'] else: self.list_id = None return self._mc_client._get(url=self._build_path(), **queryparams) ================================================ FILE: mailchimp3/entities/segments.py ================================================ from __future__ import unicode_literals from ..baseapi import BaseApi class Segments(BaseApi): def __init__(self, *args, **kwargs): super(Segments, self).__init__(*args, **kwargs) self.endpoint = 'lists' def all(self, list_id, **queryparams): """ returns the first 10 segments for a specific list. """ return self._mc_client._get(url=self._build_path(list_id, 'segments'), **queryparams) def get(self, list_id, segment_id): """ returns the specified list segment. """ return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id)) def update(self, list_id, segment_id, data): """ updates an existing list segment. """ return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data) def delete(self, list_id, segment_id): """ removes an existing list segment from the list. This cannot be undone. """ return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id)) def create(self, list_id, data): """ adds a new segment to the list. """ return self._mc_client._post(url=self._build_path(list_id, 'segments'), data=data) ================================================ FILE: mailchimp3/entities/storecartlines.py ================================================ # coding=utf-8 """ The E-commerce Store Cart Lines endpoint API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/lines/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Carts/Lines/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StoreCartLines(BaseApi): """ Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreCartLines, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.cart_id = None self.line_id = None def create(self, store_id, cart_id, data): """ Add a new line item to an existing cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "product_id": string*, "product_variant_id": string*, "quantity": integer*, "price": number* } """ self.store_id = store_id self.cart_id = cart_id if 'id' not in data: raise KeyError('The cart line must have an id') if 'product_id' not in data: raise KeyError('The cart line must have a product_id') if 'product_variant_id' not in data: raise KeyError('The cart line must have a product_variant_id') if 'quantity' not in data: raise KeyError('The cart line must have a quantity') if 'price' not in data: raise KeyError('The cart line must have a price') response = self._mc_client._post(url=self._build_path(store_id, 'carts', cart_id, 'lines'), data=data) if response is not None: self.line_id = response['id'] else: self.line_id = None return response def all(self, store_id, cart_id, get_all=False, **queryparams): """ Get information about a cart’s line items. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.cart_id = cart_id self.line_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'carts', cart_id, 'lines'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'carts', cart_id, 'lines'), **queryparams) def get(self, store_id, cart_id, line_id, **queryparams): """ Get information about a specific cart line item. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.cart_id = cart_id self.line_id = line_id return self._mc_client._get(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id), **queryparams) def update(self, store_id, cart_id, line_id, data): """ Update a specific cart line item. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.cart_id = cart_id self.line_id = line_id return self._mc_client._patch(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id), data=data) def delete(self, store_id, cart_id, line_id): """ Delete a cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` """ self.store_id = store_id self.cart_id = cart_id self.line_id = line_id return self._mc_client._delete(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id)) ================================================ FILE: mailchimp3/entities/storecarts.py ================================================ # coding=utf-8 """ The E-commerce Store Carts endpoint API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Carts/Instance.json """ from __future__ import unicode_literals import re from mailchimp3.baseapi import BaseApi from mailchimp3.entities.storecartlines import StoreCartLines class StoreCarts(BaseApi): """ Use Carts to represent unfinished e-commerce transactions. This can be used to create an Abandoned Cart workflow, or to save a consumer’s shopping cart pending a successful Order. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreCarts, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.cart_id = None self.lines = StoreCartLines(self) def create(self, store_id, data): """ Add a new cart to a store. :param store_id: The store id. :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "customer": object* { "id": string* }, "currency_code": string*, "order_total": number*, "lines": array* [ { "id": string*, "product_id": string*, "product_variant_id": string*, "quantity": integer*, "price": number* } ] } """ self.store_id = store_id if 'id' not in data: raise KeyError('The cart must have an id') if 'customer' not in data: raise KeyError('The cart must have a customer') if 'id' not in data['customer']: raise KeyError('The cart customer must have an id') if 'currency_code' not in data: raise KeyError('The cart must have a currency_code') if not re.match(r"^[A-Z]{3}$", data['currency_code']): raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code') if 'order_total' not in data: raise KeyError('The cart must have an order_total') if 'lines' not in data: raise KeyError('The cart must have at least one cart line') for line in data['lines']: if 'id' not in line: raise KeyError('Each cart line must have an id') if 'product_id' not in line: raise KeyError('Each cart line must have a product_id') if 'product_variant_id' not in line: raise KeyError('Each cart line must have a product_variant_id') if 'quantity' not in line: raise KeyError('Each cart line must have a quantity') if 'price' not in line: raise KeyError('Each cart line must have a price') response = self._mc_client._post(url=self._build_path(store_id, 'carts'), data=data) if response is not None: self.cart_id = response['id'] else: self.cart_id = None return response def all(self, store_id, get_all=False, **queryparams): """ Get information about a store’s carts. :param store_id: The store id. :type store_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.cart_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'carts'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'carts'), **queryparams) def get(self, store_id, cart_id, **queryparams): """ Get information about a specific cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.cart_id = cart_id return self._mc_client._get(url=self._build_path(store_id, 'carts', cart_id), **queryparams) def update(self, store_id, cart_id, data): """ Update a specific cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.cart_id = cart_id return self._mc_client._patch(url=self._build_path(store_id, 'carts', cart_id), data=data) def delete(self, store_id, cart_id): """ Delete a cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:class:`str` """ self.store_id = store_id self.cart_id = cart_id return self._mc_client._delete(url=self._build_path(store_id, 'carts', cart_id)) ================================================ FILE: mailchimp3/entities/storecustomers.py ================================================ # coding=utf-8 """ The E-commerce Store Customers API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/customers/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Customers/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_email class StoreCustomers(BaseApi): """ Add Customers to your Store to track their orders and to view E-Commerce Data for your MailChimp lists and campaigns. Each Customer is connected to a MailChimp list member, so adding a Customer can also add or update a list member. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreCustomers, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.customer_id = None def create(self, store_id, data): """ Add a new customer to a store. :param store_id: The store id. :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "email_address": string*, "opt_in_status": boolean* } """ self.store_id = store_id if 'id' not in data: raise KeyError('The store customer must have an id') if 'email_address' not in data: raise KeyError('The store customer must have an email_address') check_email(data['email_address']) if 'opt_in_status' not in data: raise KeyError('The store customer must have an opt_in_status') if data['opt_in_status'] not in [True, False]: raise TypeError('The opt_in_status must be True or False') response = self._mc_client._post(url=self._build_path(store_id, 'customers'), data=data) if response is not None: self.customer_id = response['id'] else: self.customer_id = None return response def all(self, store_id, get_all=False, **queryparams): """ Get information about a store’s customers. :param store_id: The store id. :type store_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['email_address'] = string """ self.store_id = store_id self.customer_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'customers'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'customers'), **queryparams) def get(self, store_id, customer_id, **queryparams): """ Get information about a specific customer. :param store_id: The store id. :type store_id: :py:class:`str` :param customer_id: The id for the customer of a store. :type customer_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.customer_id = customer_id return self._mc_client._get(url=self._build_path(store_id, 'customers', customer_id), **queryparams) def update(self, store_id, customer_id, data): """ Update a customer. :param store_id: The store id. :type store_id: :py:class:`str` :param customer_id: The id for the customer of a store. :type customer_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.customer_id = customer_id return self._mc_client._patch(url=self._build_path(store_id, 'customers', customer_id), data=data) def create_or_update(self, store_id, customer_id, data): """ Add or update a customer. :param store_id: The store id. :type store_id: :py:class:`str` :param customer_id: The id for the customer of a store. :type customer_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "email_address": string*, "opt_in_status": boolean } """ self.store_id = store_id self.customer_id = customer_id if 'id' not in data: raise KeyError('The store customer must have an id') if 'email_address' not in data: raise KeyError('Each store customer must have an email_address') check_email(data['email_address']) if 'opt_in_status' not in data: raise KeyError('The store customer must have an opt_in_status') if data['opt_in_status'] not in [True, False]: raise TypeError('The opt_in_status must be True or False') return self._mc_client._put(url=self._build_path(store_id, 'customers', customer_id), data=data) def delete(self, store_id, customer_id): """ Delete a customer from a store. :param store_id: The store id. :type store_id: :py:class:`str` :param customer_id: The id for the customer of a store. :type customer_id: :py:class:`str` """ self.store_id = store_id self.customer_id = customer_id return self._mc_client._delete(url=self._build_path(store_id, 'customers', customer_id)) ================================================ FILE: mailchimp3/entities/storeorderlines.py ================================================ # coding=utf-8 """ The E-commerce Store Orders endpoint API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/orders/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Customers/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StoreOrderLines(BaseApi): """ Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreOrderLines, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.order_id = None self.line_id = None def create(self, store_id, order_id, data): """ Add a new line item to an existing order. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "product_id": string*, "product_variant_id": string*, "quantity": integer*, "price": number* } """ self.store_id = store_id self.order_id = order_id if 'id' not in data: raise KeyError('The order line must have an id') if 'product_id' not in data: raise KeyError('The order line must have a product_id') if 'product_variant_id' not in data: raise KeyError('The order line must have a product_variant_id') if 'quantity' not in data: raise KeyError('The order line must have a quantity') if 'price' not in data: raise KeyError('The order line must have a price') response = self._mc_client._post(url=self._build_path(store_id, 'orders', order_id, 'lines')) if response is not None: self.line_id = response['id'] else: self.line_id = None return response def all(self, store_id, order_id, get_all=False, **queryparams): """ Get information about an order’s line items. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.order_id = order_id self.line_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'orders', order_id, 'lines'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'orders', order_id, 'lines'), **queryparams) def get(self, store_id, order_id, line_id, **queryparams): """ Get information about a specific order line item. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.order_id = order_id self.line_id = line_id return self._mc_client._get(url=self._build_path(store_id, 'orders', order_id, 'lines', line_id), **queryparams) def update(self, store_id, order_id, line_id, data): """ Update a specific order line item. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.order_id = order_id self.line_id = line_id return self._mc_client._patch(url=self._build_path(store_id, 'orders', order_id, 'lines', line_id), data=data) def delete(self, store_id, order_id, line_id): """ Delete a specific order line item. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param line_id: The id for the line item of a cart. :type line_id: :py:class:`str` """ self.store_id = store_id self.order_id = order_id self.line_id = line_id return self._mc_client._delete(url=self._build_path(store_id, 'orders', order_id, 'lines', line_id)) ================================================ FILE: mailchimp3/entities/storeorders.py ================================================ # coding=utf-8 """ The E-commerce Store Orders endpoint API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/orders/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Customers/Instance.json """ from __future__ import unicode_literals import re from mailchimp3.baseapi import BaseApi from mailchimp3.entities.storeorderlines import StoreOrderLines class StoreOrders(BaseApi): """ Orders represent successful e-commerce transactions, and this data can be used to provide more detailed campaign reports, track sales, and personalize emails to your targeted consumers, and view other e-commerce data in your MailChimp account. .. note:: If a financial_status or fulfillment_status value is provided when creating or updating an order, it will trigger a notification email if they have been designed and enabled in your account. The following sets of statuses trigger the following notification types: financial_status = 'paid' -> Order Invoice financial_status = 'pending' -> Order Confirmation financial_status = 'refunded' -> Refund Confirmation financial_status = 'cancelled' -> Cancellation Confirmation fulfillment_status = 'shipped' -> Shipping Confirmation The current list of notification types and triggers can be found at http://developer.mailchimp.com/documentation/mailchimp/guides/getting-started-with-ecommerce/#order-notifications and should be consulted in the event of any changes """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreOrders, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.order_id = None self.lines = StoreOrderLines(self) def create(self, store_id, data): """ Add a new order to a store. :param store_id: The store id. :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "customer": object* { "'id": string* }, "curency_code": string*, "order_total": number*, "lines": array* [ { "id": string*, "product_id": string*, "product_variant_id": string*, "quantity": integer*, "price": number* } ] } """ self.store_id = store_id if 'id' not in data: raise KeyError('The order must have an id') if 'customer' not in data: raise KeyError('The order must have a customer') if 'id' not in data['customer']: raise KeyError('The order customer must have an id') if 'currency_code' not in data: raise KeyError('The order must have a currency_code') if not re.match(r"^[A-Z]{3}$", data['currency_code']): raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code') if 'order_total' not in data: raise KeyError('The order must have an order_total') if 'lines' not in data: raise KeyError('The order must have at least one order line') for line in data['lines']: if 'id' not in line: raise KeyError('Each order line must have an id') if 'product_id' not in line: raise KeyError('Each order line must have a product_id') if 'product_variant_id' not in line: raise KeyError('Each order line must have a product_variant_id') if 'quantity' not in line: raise KeyError('Each order line must have a quantity') if 'price' not in line: raise KeyError('Each order line must have a price') response = self._mc_client._post(url=self._build_path(store_id, 'orders'), data=data) if response is not None: self.order_id = response['id'] else: self.order_id = None return response def all(self, store_id, get_all=False, **queryparams): """ Get information about a store’s orders. :param store_id: The store id. :type store_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['customer_id'] = string """ self.store_id = store_id self.order_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'orders'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'orders'), **queryparams) def get(self, store_id, order_id, **queryparams): """ Get information about a specific order. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.order_id = order_id return self._mc_client._get(url=self._build_path(store_id, 'orders', order_id), **queryparams) def update(self, store_id, order_id, data): """ Update a specific order. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.order_id = order_id return self._mc_client._patch(url=self._build_path(store_id, 'orders', order_id), data=data) def delete(self, store_id, order_id): """ Delete an order. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type order_id: :py:class:`str` """ self.store_id = store_id self.order_id = order_id return self._mc_client._delete(url=self._build_path(store_id, 'orders', order_id)) ================================================ FILE: mailchimp3/entities/storeproductimages.py ================================================ # coding=utf-8 """ The E-commerce Store Product Images API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/products/images/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Products/Images/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StoreProductImages(BaseApi): """ A Product Image represents a specific product image. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreProductImages, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.product_id = None self.image_id = None def create(self, store_id, product_id, data): """ Add a new image to the product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "url": string* } """ self.store_id = store_id self.product_id = product_id if 'id' not in data: raise KeyError('The product image must have an id') if 'title' not in data: raise KeyError('The product image must have a url') response = self._mc_client._post(url=self._build_path(store_id, 'products', product_id, 'images'), data=data) if response is not None: self.image_id = response['id'] else: self.image_id = None return response def all(self, store_id, product_id, get_all=False, **queryparams): """ Get information about a product’s images. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.product_id = product_id self.image_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'products', product_id, 'images'), **queryparams) else: return self._mc_client._post(url=self._build_path(store_id, 'products', product_id, 'images'), **queryparams) def get(self, store_id, product_id, image_id, **queryparams): """ Get information about a specific product image. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param image_id: The id for the product image. :type image_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.product_id = product_id self.image_id = image_id return self._mc_client._post( url=self._build_path(store_id, 'products', product_id, 'images', image_id), **queryparams ) def update(self, store_id, product_id, image_id, data): """ Update a product image. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param image_id: The id for the product image. :type image_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.product_id = product_id self.image_id = image_id return self._mc_client._patch( url=self._build_path(store_id, 'products', product_id, 'images', image_id), data=data ) def delete(self, store_id, product_id, image_id): """ Delete a product image. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param image_id: The id for the product image. :type image_id: :py:class:`str` """ self.store_id = store_id self.product_id = product_id self.image_id = image_id return self._mc_client._delete(url=self._build_path(store_id, 'products', product_id, 'images', image_id)) ================================================ FILE: mailchimp3/entities/storeproducts.py ================================================ # coding=utf-8 """ The E-commerce Store Products API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/products/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Products/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.storeproductimages import StoreProductImages from mailchimp3.entities.storeproductvariants import StoreProductVariants class StoreProducts(BaseApi): """ E-commerce items for sale in your store need to be created as Products so you can add the items to a Cart or an Order. Each Product requires at least one Product Variant. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreProducts, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.product_id = None self.images = StoreProductImages(self) self.variants = StoreProductVariants(self) def create(self, store_id, data): """ Add a new product to a store. :param store_id: The store id. :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "title": string*, "variants": array* [ { "id": string*, "title": string* } ] } """ self.store_id = store_id if 'id' not in data: raise KeyError('The product must have an id') if 'title' not in data: raise KeyError('The product must have a title') if 'variants' not in data: raise KeyError('The product must have at least one variant') for variant in data['variants']: if 'id' not in variant: raise KeyError('Each product variant must have an id') if 'title' not in variant: raise KeyError('Each product variant must have a title') response = self._mc_client._post(url=self._build_path(store_id, 'products'), data=data) if response is not None: self.product_id = response['id'] else: self.product_id = None return response def all(self, store_id, get_all=False, **queryparams): """ Get information about a store’s products. :param store_id: The store id. :type store_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.product_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'products'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'products'), **queryparams) def get(self, store_id, product_id, **queryparams): """ Get information about a specific product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.product_id = product_id return self._mc_client._get(url=self._build_path(store_id, 'products', product_id), **queryparams) def update(self, store_id, product_id, data): """ Update a product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.product_id = product_id return self._mc_client._patch( url=self._build_path(store_id, 'products', product_id), data=data ) def delete(self, store_id, product_id): """ Delete a product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` """ self.store_id = store_id self.product_id = product_id return self._mc_client._delete(url=self._build_path(store_id, 'products', product_id)) ================================================ FILE: mailchimp3/entities/storeproductvariants.py ================================================ # coding=utf-8 """ The E-commerce Store Product Variants API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/products/variants/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Products/Variants/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StoreProductVariants(BaseApi): """ A Product Variant represents a specific item for purchase, and is contained within a parent Product. At least one Product Variant is required for each Product. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(StoreProductVariants, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.product_id = None self.variant_id = None def create(self, store_id, product_id, data): """ Add a new variant to the product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "title": string* } """ self.store_id = store_id self.product_id = product_id if 'id' not in data: raise KeyError('The product variant must have an id') if 'title' not in data: raise KeyError('The product variant must have a title') response = self._mc_client._post(url=self._build_path(store_id, 'products', product_id, 'variants'), data=data) if response is not None: self.variant_id = response['id'] else: self.variant_id = None return response def all(self, store_id, product_id, get_all=False, **queryparams): """ Get information about a product’s variants. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.product_id = product_id self.variant_id = None if get_all: return self._iterate(url=self._build_path(store_id, 'products', product_id, 'variants'), **queryparams) else: return self._mc_client._get( url=self._build_path(store_id, 'products', product_id, 'variants'), **queryparams ) def get(self, store_id, product_id, variant_id, **queryparams): """ Get information about a specific product variant. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param variant_id: The id for the product variant. :type variant_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id self.product_id = product_id self.variant_id = variant_id return self._mc_client._get( url=self._build_path(store_id, 'products', product_id, 'variants', variant_id), **queryparams ) def update(self, store_id, product_id, variant_id, data): """ Update a product variant. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param variant_id: The id for the product variant. :type variant_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id self.product_id = product_id self.variant_id = variant_id return self._mc_client._patch( url=self._build_path(store_id, 'products', product_id, 'variants', variant_id), data=data ) def create_or_update(self, store_id, product_id, variant_id, data): """ Add or update a product variant. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param variant_id: The id for the product variant. :type variant_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "title": string* } """ self.store_id = store_id self.product_id = product_id self.variant_id = variant_id if 'id' not in data: raise KeyError('The product variant must have an id') if 'title' not in data: raise KeyError('The product variant must have a title') return self._mc_client._put( url=self._build_path(store_id, 'products', product_id, 'variants', variant_id), data=data ) def delete(self, store_id, product_id, variant_id): """ Delete a product variant. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_id: :py:class:`str` :param variant_id: The id for the product variant. :type variant_id: :py:class:`str` """ self.store_id = store_id self.product_id = product_id self.variant_id = variant_id return self._mc_client._delete(url=self._build_path(store_id, 'products', product_id, 'variants', variant_id)) ================================================ FILE: mailchimp3/entities/storepromocodes.py ================================================ # coding=utf-8 """ The E-commerce Stores Promo CodesAPI endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/promo-rules """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StorePromoCodes(BaseApi): """ Promo Promo codes can be created for a given promo rule. All the promo codes under a promo rule share the generic information defined for that rule like the amount, type, expiration date etc. """ def __init__(self, *args, **kwargs): """ Initialize the Endpoint :param args: :param kwargs: """ super(StorePromoCodes, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None def create(self, store_id, promo_rule_id, data): """ Add a new promo code to a store. :param store_id: The store id :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict' data = { "id": string*, "code": string*, "redemption_url": string*, "usage_count": string, "enabled": boolean, "created_at_foreign": string, "updated_at_foreign": string, } """ self.store_id = store_id if 'id' not in data: raise KeyError('The promo code must have an id') if 'code' not in data: raise KeyError('This promo code must have a code') if 'redemption_url' not in data: raise KeyError('This promo code must have a redemption url') response = self._mc_client._post(url=self._build_path(store_id, 'promo-rules', promo_rule_id, 'promo-codes'), data=data) if response is not None: return response def all(self, store_id, promo_rule_id, get_all=False, **queryparams): """ Get information about a store’s promo codes. :param store_id: The store's id :type store_id: `str` :param promo_rule_id: The store promo rule id :type store_id: `str` :param get_all: :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id=store_id self.promo_rule_id=promo_rule_id if get_all: return self._iterate(url=self._build_path(store_id, 'promo-rules', promo_rule_id, 'promo-codes'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'promo-rule', promo_rule_id), **queryparams) def get(self, store_id, promo_rule_id, promo_code_id, **queryparams): """ Get information about a specific promo code. :param store_id: The store's id :type store_id: `string` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.promo_rule_id = promo_rule_id self.promo_code_id = promo_code_id return self._mc_client._get(url=self._build_path(store_id, 'promo-rules', promo_rule_id, 'promo-codes', promo_code_id), **queryparams) def update(self, store_id, promo_rule_id, promo_code_id, data): """ Update a promo code :param store_id: The store id :type :py:class:`str` :param promo_rule_id: The id for the promo rule of a store. :type :py:class:`str` :param promo_code_id: The id for the promo code of a store. :type :py:class:`str` :param data: :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string, "title": string, "description": string, "starts_at": string, "ends_at": string, "amount": number, "type": string, "target": string, "enabled": boolean, "created_at_foreign": string, "updated_at_foreign": string, } """ self.store_id = store_id self.promo_rule_id = promo_rule_id self.promo_code_id = promo_code_id return self._mc_client._patch(url=self._build_path(store_id, 'promo-rules', promo_rule_id, 'promo-codes', promo_code_id), data=data) def delete(self, store_id, promo_rule_id, promo_code_id): """ Delete a promo code :param store_id: The store id :type :py:class:`str` :param promo_rule_id: The id for the promo rule of a store. :type :py:class:`str` :param promo_code_id: The id for the promo code of a store. :type :py:class:`str` """ self.store_id=store_id self.promo_rule_id=promo_rule_id return self._mc_client._delete(url=self._build_path(store_id, 'promo-rules', promo_rule_id, 'promo-codes', promo_code_id)) ================================================ FILE: mailchimp3/entities/storepromorules.py ================================================ # coding=utf-8 """ The E-commerce Stores Promo Rules API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/promo-rules """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class StorePromoRules(BaseApi): """ Promo Rules help you create promo codes for your campaigns. Promo Rules define generic information about promo codes like expiration time, start time, amount of discount being offered etc """ def __init__(self, *args, **kwargs): """ Initialize the Endpoint :param args: :param kwargs: """ super(StorePromoRules, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None def create(self, store_id, data): """ Add new promo rule to a store :param store_id: The store id :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict' data = { "id": string*, "title": string, "description": string*, "starts_at": string, "ends_at": string, "amount": number*, "type": string*, "target": string*, "enabled": boolean, "created_at_foreign": string, "updated_at_foreign": string, } """ self.store_id = store_id if 'id' not in data: raise KeyError('The promo rule must have an id') if 'description' not in data: raise KeyError('This promo rule must have a description') if 'amount' not in data: raise KeyError('This promo rule must have an amount') if 'target' not in data: raise KeyError('This promo rule must apply to a target (example per_item, total, or shipping') response = self._mc_client._post(url=self._build_path(store_id, 'promo-rules'), data=data) if response is not None: return response def all(self, store_id, get_all=False, **queryparams): """ Get information about a store’s promo rules. :param store_id: The store's id :type store_id: `str` :param get_all: :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id if get_all: return self._iterate(url=self._build_path(store_id, 'promo-rules'), **queryparams) else: return self._mc_client._get(url=self._build_path(store_id, 'promo-rules'), **queryparams) def get(self, store_id, promo_rule_id, **queryparams): """ Get information about a specific promo rule. :param store_id: The store's id :type store_id: `string` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = store_id self.promo_rule_id = promo_rule_id return self._mc_client._get(url=self._build_path(store_id, 'promo-rules', promo_rule_id), **queryparams) def update(self, store_id, promo_rule_id, data): """ Update a promo rule :param store_id: The store id :type :py:class:`str` :param promo_rule_id: The id for the promo rule of a store. :type :py:class:`str` :param data: :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string, "title": string, "description": string, "starts_at": string, "ends_at": string, "amount": number, "type": string, "target": string, "enabled": boolean, "created_at_foreign": string, "updated_at_foreign": string, } """ self.store_id = store_id self.promo_rule_id = promo_rule_id return self._mc_client._patch(url=self._build_path(store_id, 'promo-rules', promo_rule_id), data=data) def delete(self, store_id, promo_rule_id): """ Delete a promo rule :param store_id: The store id :type :py:class:`str` :param promo_rule_id: The id for the promo rule of a store. :type :py:class:`str` """ self.store_id=store_id self.promo_rule_id=promo_rule_id return self._mc_client._delete(url=self._build_path(store_id, 'promo-rules', promo_rule_id)) ================================================ FILE: mailchimp3/entities/stores.py ================================================ # coding=utf-8 """ The E-commerce Stores API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/ Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Instance.json """ from __future__ import unicode_literals import re from mailchimp3.baseapi import BaseApi from mailchimp3.entities.storecarts import StoreCarts from mailchimp3.entities.storecustomers import StoreCustomers from mailchimp3.entities.storeorders import StoreOrders from mailchimp3.entities.storeproducts import StoreProducts class Stores(BaseApi): """ Connect your E-commerce Store to MailChimp to take advantage of powerful reporting and personalization features and to learn more about your customers. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Stores, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.carts = StoreCarts(self) self.customers = StoreCustomers(self) self.orders = StoreOrders(self) self.products = StoreProducts(self) def create(self, data): """ Add a new store to your MailChimp account. Error checking on the currency code verifies that it is in the correct three-letter, all-caps format as specified by ISO 4217 but does not check that it is a valid code as the list of valid codes changes over time. :param data: The request body parameters :type data: :py:class:`dict` data = { "id": string*, "list_id": string*, "name": string*, "currency_code": string* } """ if 'id' not in data: raise KeyError('The store must have an id') if 'list_id' not in data: raise KeyError('The store must have a list_id') if 'name' not in data: raise KeyError('The store must have a name') if 'currency_code' not in data: raise KeyError('The store must have a currency_code') if not re.match(r"^[A-Z]{3}$", data['currency_code']): raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.store_id = response['id'] else: self.store_id = None return response def all(self, get_all=False, **queryparams): """ Get information about all stores in the account. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.store_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, store_id, **queryparams): """ Get information about a specific store. :param store_id: The store id. :type store_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.store_id = store_id return self._mc_client._get(url=self._build_path(store_id), **queryparams) def update(self, store_id, data): """ Update a store. :param store_id: The store id. :type store_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` """ self.store_id = store_id return self._mc_client._patch(url=self._build_path(store_id), data=data) def delete(self, store_id): """ Delete a store. Deleting a store will also delete any associated subresources, including Customers, Orders, Products, and Carts. :param store_id: The store id. :type store_id: :py:class:`str` """ self.store_id = store_id return self._mc_client._delete(url=self._build_path(store_id)) ================================================ FILE: mailchimp3/entities/templatedefaultcontent.py ================================================ # coding=utf-8 """ The Template Default Content API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/templates/default-content/ Schema: https://api.mailchimp.com/schema/3.0/Templates/Defaultcontent/Collection.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class TemplateDefaultContent(BaseApi): """ Manage the default content for a MailChimp template. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(TemplateDefaultContent, self).__init__(*args, **kwargs) self.endpoint = 'templates' self.template_id = None def all(self, template_id, **queryparams): """ Get the sections that you can edit in a template, including each section’s default content. :param template_id: The unique id for the template. :type template_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.template_id = template_id return self._mc_client._get(url=self._build_path(template_id, 'default-content'), **queryparams) ================================================ FILE: mailchimp3/entities/templatefolders.py ================================================ # coding=utf-8 """ The Template Folders API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/template-folders/ Schema: https://api.mailchimp.com/schema/3.0/TemplateFolders/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi class TemplateFolders(BaseApi): """ Organize your templates using folders. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(TemplateFolders, self).__init__(*args, **kwargs) self.endpoint = 'template-folders' self.folder_id = None def create(self, data): """ Create a new template folder. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ if 'name' not in data: raise KeyError('The template folder must have a name') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.folder_id = response['id'] else: self.folder_id = None return response def all(self, get_all=False, **queryparams): """ Get all folders used to organize templates. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer """ self.folder_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, folder_id, **queryparams): """ Get information about a specific folder used to organize templates. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.folder_id = folder_id return self._mc_client._get(url=self._build_path(folder_id), **queryparams) def update(self, folder_id, data): """ Update a specific folder used to organize templates. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string* } """ if 'name' not in data: raise KeyError('The template folder must have a name') self.folder_id = folder_id return self._mc_client._patch(url=self._build_path(folder_id), data=data) def delete(self, folder_id): """ Delete a specific template folder, and mark all the templates in the folder as ‘unfiled’. :param folder_id: The unique id for the File Manager folder. :type folder_id: :py:class:`str` """ self.folder_id = folder_id return self._mc_client._delete(url=self._build_path(folder_id)) ================================================ FILE: mailchimp3/entities/templates.py ================================================ # coding=utf-8 """ The Templates API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/templates/ Schema: https://api.mailchimp.com/schema/3.0/Templates/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.entities.templatedefaultcontent import TemplateDefaultContent class Templates(BaseApi): """ Manage your MailChimp templates. A template is an HTML file used to create the layout and basic design for a campaign. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(Templates, self).__init__(*args, **kwargs) self.endpoint = 'templates' self.template_id = None self.default_content = TemplateDefaultContent(self) def create(self, data): """ Create a new template for the account. Only Classic templates are supported. :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "html": string* } """ if 'name' not in data: raise KeyError('The template must have a name') if 'html' not in data: raise KeyError('The template must have html') response = self._mc_client._post(url=self._build_path(), data=data) if response is not None: self.template_id = response['id'] else: self.template_id = None return response def all(self, get_all=False, **queryparams): """ Get a list of an account’s available templates. :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] queryparams['count'] = integer queryparams['offset'] = integer queryparams['created_by'] = string queryparams['before_created_at'] = string queryparams['since_created_at'] = string queryparams['type'] = string queryparams['folder_id'] = string """ self.template_id = None if get_all: return self._iterate(url=self._build_path(), **queryparams) else: return self._mc_client._get(url=self._build_path(), **queryparams) def get(self, template_id, **queryparams): """ Get information about a specific template. :param template_id: The unique id for the template. :type template_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = [] """ self.template_id = template_id return self._mc_client._get(url=self._build_path(template_id), **queryparams) def update(self, template_id, data): """ Update the name, HTML, or folder_id of an existing template. :param template_id: The unique id for the template. :type template_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "name": string*, "html": string* } """ if 'name' not in data: raise KeyError('The template must have a name') if 'html' not in data: raise KeyError('The template must have html') self.template_id = template_id return self._mc_client._patch(url=self._build_path(template_id), data=data) def delete(self, template_id): """ Delete a specific template. :param template_id: The unique id for the template. :type template_id: :py:class:`str` """ self.template_id = template_id return self._mc_client._delete(url=self._build_path(template_id)) ================================================ FILE: mailchimp3/helpers.py ================================================ # coding=utf-8 """ Helper functions to perform simple tasks for multiple areas of the API """ import hashlib import re HTTP_METHOD_ACTION_MATCHING = { 'get': 'GET', 'create': 'POST', 'update': 'PATCH', 'create_or_update': 'PUT', 'delete': 'DELETE' } def get_subscriber_hash(member_email): """ The MD5 hash of the lowercase version of the list member's email. Used as subscriber_hash :param member_email: The member's email address :type member_email: :py:class:`str` :returns: The MD5 hash in hex :rtype: :py:class:`str` """ check_email(member_email) member_email = member_email.lower().encode() m = hashlib.md5(member_email) return m.hexdigest() def check_subscriber_hash(potential_hash): """ Check the passed value to see if it matches a 32 character hex number that MD5 generates as output, or compute that value assuming that the input is an email address. :param potential_hash: A value to be passed to any of the endpoints that expect an MD5 of an email address :type potential_hash: :py:class:`str` :returns: A valid MD5 hash in hex :rtype: :py:class:`str` """ if re.match(r"^[0-9a-f]{32}$", potential_hash): return potential_hash else: return get_subscriber_hash(potential_hash) def check_email(email): """ Function that verifies that the string passed is a valid email address. Regex for email validation based on MailChimp limits: http://kb.mailchimp.com/accounts/management/international-characters-in-mailchimp :param email: The potential email address :type email: :py:class:`str` :return: Nothing """ if not re.match(r".+@.+\..+", email): raise ValueError('String passed is not a valid email address') return def check_url(url): """ Function that verifies that the string passed is a valid url. Original regex author Diego Perini (http://www.iport.it) regex ported to Python by adamrofer (https://github.com/adamrofer) Used under MIT license. :param url: :return: Nothing """ URL_REGEX = re.compile( u"^" u"(?:(?:https?|ftp)://)" u"(?:\\S+(?::\\S*)?@)?" u"(?:" u"(?!(?:10|127)(?:\\.\\d{1,3}){3})" u"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" u"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" u"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" u"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" u"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" u"|" u"(?:(?:[a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)" u"(?:\\.(?:[a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)*" u"(?:\\.(?:[a-z\u00a1-\uffff]{2,}))" u")" u"(?::\\d{2,5})?" u"(?:/\\S*)?" u"$" , re.UNICODE) if not re.match(URL_REGEX, url): raise ValueError('String passed is not a valid url') return def merge_results(x, y): """ Given two dicts, x and y, merge them into a new dict as a shallow copy. The result only differs from `x.update(y)` in the way that it handles list values when both x and y have list values for the same key. In which case the returned dictionary, z, has a value according to: z[key] = x[key] + z[key] :param x: The first dictionary :type x: :py:class:`dict` :param y: The second dictionary :type y: :py:class:`dict` :returns: The merged dictionary :rtype: :py:class:`dict` """ z = x.copy() for key, value in y.items(): if isinstance(value, list) and isinstance(z.get(key), list): z[key] += value else: z[key] = value return z ================================================ FILE: mailchimp3/mailchimpclient.py ================================================ # coding=utf-8 """ Mailchimp v3 Api SDK Documentation: http://developer.mailchimp.com/documentation/mailchimp/ """ from __future__ import unicode_literals import functools import re import requests from requests.auth import HTTPBasicAuth # Handle library reorganisation Python 2 > Python 3. try: from urllib.parse import urljoin from urllib.parse import urlencode except ImportError: from urlparse import urljoin from urllib import urlencode import logging _logger = logging.getLogger('mailchimp3.client') def _enabled_or_noop(fn): @functools.wraps(fn) def wrapper(self, *args, **kwargs): if self.enabled: return fn(self, *args, **kwargs) return wrapper class MailChimpError(Exception): pass def _raise_response_error(r): """ Return a MailChimpError to which we pass: - the response object - the response's JSON data if found. """ error_data = {"response": r} try: json_data = r.json() except ValueError: # in case of a 500 error, the response might not be a JSON pass else: error_data.update(json_data) raise MailChimpError(error_data) class MailChimpClient(object): """ MailChimp class to communicate with the v3 API """ def __init__(self, mc_api=None, mc_user='python-mailchimp', access_token=None, enabled=True, timeout=None, request_hooks=None, request_headers=None): """ Initialize the class with your optional user_id and required api_key. If `enabled` is not True, these methods become no-ops. This is particularly useful for testing or disabling with configuration. :param mc_api: Mailchimp API key :type mc_api: :py:class:`str` :param mc_user: Mailchimp user id :type mc_user: :py:class:`str` :param access_token: The OAuth access token :type access_token: :py:class:`str` :param enabled: Whether the API should execute any requests :type enabled: :py:class:`bool` :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) ` tuple. :type timeout: float or tuple :param request_hooks: (optional) Hooks for :py:func:`requests.requests`. :type request_hooks: :py:class:`dict` :param request_headers: (optional) Headers for :py:func:`requests.requests`. :type request_headers: :py:class:`dict` """ super(MailChimpClient, self).__init__() self.enabled = enabled self.timeout = timeout if access_token: self.auth = MailChimpOAuth(access_token) self.base_url = self.auth.get_base_url() + '/3.0/' elif mc_api: if not re.match(r"^[0-9a-f]{32}$", mc_api.split('-')[0]): raise ValueError('The API key that you have entered is not valid, did you enter a username by mistake?\n' 'The order of arguments for API key and username has reversed in 2.1.0') self.auth = HTTPBasicAuth(mc_user, mc_api) datacenter = mc_api.split('-').pop() self.base_url = 'https://{0}.api.mailchimp.com/3.0/'.format(datacenter) else: raise Exception('You must provide an OAuth access token or API key') self.request_headers = request_headers or requests.utils.default_headers() self.request_hooks = request_hooks or requests.hooks.default_hooks() def _make_request(self, **kwargs): _logger.info(u'{method} Request: {url}'.format(**kwargs)) if kwargs.get('json'): _logger.info('PAYLOAD: {json}'.format(**kwargs)) response = requests.request(**kwargs) _logger.info(u'{method} Response: {status}'\ .format(method=kwargs['method'], status=response.status_code)) return response @_enabled_or_noop def _post(self, url, data=None): """ Handle authenticated POST requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :param data: The request body parameters :type data: :py:data:`none` or :py:class:`dict` :returns: The JSON output from the API or an error message """ url = urljoin(self.base_url, url) try: r = self._make_request(**dict( method='POST', url=url, json=data, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: _raise_response_error(r) if r.status_code == 204: return None return r.json() @_enabled_or_noop def _get(self, url, **queryparams): """ Handle authenticated GET requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :param queryparams: The query string parameters :returns: The JSON output from the API """ url = urljoin(self.base_url, url) if len(queryparams): url += '?' + urlencode(queryparams) try: r = self._make_request(**dict( method='GET', url=url, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: _raise_response_error(r) return r.json() @_enabled_or_noop def _delete(self, url): """ Handle authenticated DELETE requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :returns: The JSON output from the API """ url = urljoin(self.base_url, url) try: r = self._make_request(**dict( method='DELETE', url=url, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: _raise_response_error(r) if r.status_code == 204: return return r.json() @_enabled_or_noop def _patch(self, url, data=None): """ Handle authenticated PATCH requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :param data: The request body parameters :type data: :py:data:`none` or :py:class:`dict` :returns: The JSON output from the API """ url = urljoin(self.base_url, url) try: r = self._make_request(**dict( method='PATCH', url=url, json=data, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: _raise_response_error(r) return r.json() @_enabled_or_noop def _put(self, url, data=None): """ Handle authenticated PUT requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :param data: The request body parameters :type data: :py:data:`none` or :py:class:`dict` :returns: The JSON output from the API """ url = urljoin(self.base_url, url) try: r = self._make_request(**dict( method='PUT', url=url, json=data, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: _raise_response_error(r) return r.json() class MailChimpOAuth(requests.auth.AuthBase): """ Authentication class for authentication with OAuth2. Acquiring an OAuth2 for MailChimp can be done by following the instructions in the documentation found at http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-oauth2/ """ def __init__(self, access_token): """ Initialize the OAuth and save the access token :param access_token: The access token provided by OAuth authentication :type access_token: :py:class:`str` """ self._access_token = access_token def __call__(self, r): """ Authorize with the access token provided in __init__ """ r.headers['Authorization'] = 'OAuth ' + self._access_token return r def get_metadata(self): """ Get the metadata returned after authentication """ try: r = requests.get('https://login.mailchimp.com/oauth2/metadata', auth=self) except requests.exceptions.RequestException as e: raise e else: r.raise_for_status() output = r.json() if 'error' in output: raise requests.exceptions.RequestException(output['error']) return output def get_base_url(self): """ Get the base_url from the authentication metadata """ try: return self.get_metadata()['api_endpoint'] except requests.exceptions.RequestException: raise ================================================ FILE: setup.cfg ================================================ [bdist_wheel] universal = 1 ================================================ FILE: setup.py ================================================ #!/usr/bin/env python import os from setuptools import setup, find_packages README = os.path.join(os.path.dirname(__file__), 'README.rst') # When running tests using tox, README.md is not found try: with open(README) as file: long_description = file.read() except Exception: long_description = '' setup( name='mailchimp3', version='3.0.21', description='A python client for v3 of MailChimp API', long_description=long_description, url='https://github.com/charlesthk/python-mailchimp', author='Charles TISSIER', author_email='charles@vingtcinq.io', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', ], keywords='mailchimp api v3 client wrapper', packages=find_packages(), install_requires=['requests>=2.7.0'], # test_suite='tests', ) ================================================ FILE: test.py ================================================ # coding=utf-8 """ Some basic tests to verify that the wrapper is working """ from mailchimp3 import MailChimp client = MailChimp('MAILCHIMP_USER', 'MAILCHIMP_SECRET') print client.lists.all(fields="lists.name,lists.id") print client.authorized_apps.all(get_all=False) print client.automations.all(get_all=True)