listmonk 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -0,0 +1,161 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ .idea/
161
+ settings.json
listmonk-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Michael Kennedy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.1
2
+ Name: listmonk
3
+ Version: 0.1.0
4
+ Summary: Listmonk Email App API Client for Python
5
+ Project-URL: Homepage, https://github.com/mikeckennedy/listmonk
6
+ Project-URL: Tracker, https://github.com/mikeckennedy/listmonk/issues
7
+ Project-URL: Source, https://github.com/mikeckennedy/listmonk
8
+ Author-email: Michael Kennedy <michael@talkpython.fm>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: api-client,email,marketing,newsletters
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Requires-Python: >=3.8
22
+ Requires-Dist: httpx
23
+ Requires-Dist: pydantic
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Listmonk Email App API Client for Python
27
+
28
+ Client for the for open source, self-hosted [Listmonk email platform](https://listmonk.app) based on
29
+ [httpx](https://www.python-httpx.org) and [pydantic](https://pydantic.dev).
30
+
31
+ `listmonk` is intended for integrating your Listmonk instance into your web app. The [Listmonk API is extensive](https://listmonk.app/docs/apis/apis/) but this only covers the subset that most developers will need for common SaaS actions such as subscribe, unsubscribe, and segmentate users (into separate lists).
32
+
33
+ So while it doesn't currently cover every endpoint (for example you cannot create a list programatically nor can you edit HTML templates for campaigns over APIs) it will likely work for you. That said, PRs are weclome.
34
+
35
+ 🔀 Async is currently planned but not yet implemented. With the httpx-base, it should be trivial if needed.
36
+
37
+ ## Core Features
38
+
39
+ * ➕**Add a subscriber** to your subscribed users.
40
+ * 🙎 Get **subscriber details** by email, ID, UUID, and more.
41
+ * 📝 **Modify subscriber details** (including custom attribute collection).
42
+ * 🔍 **Search** your users based on app and custom attributes.
43
+ * 🏥 Check the **health and connectivity** of your instance.
44
+ * 👥 Retrieve your **segmentation lists**, list details, and subscribers.
45
+ * 🙅 Unsubscribe and block users who don't want to be contacted further.
46
+ * 💥 Completely delete a subscriber from your instance.
47
+ * 📧 Send transactional email with template data (i.e. password reset emails).
48
+
49
+ ## Installation
50
+
51
+ Just `pip install listmonk`
52
+
53
+
54
+ ## Usage
55
+
56
+ ```python
57
+
58
+ import listmonk
59
+ listmonk.set_url_base('https://yourlistmonkurl.com')
60
+
61
+ listmonk.login('sammyz', '1234')
62
+ valid: bool = listmonk.verify_login()
63
+
64
+ # Is it alive and working?
65
+ up: bool = listmonk.is_healthy()
66
+
67
+ # Read data about your lists
68
+ lists: list[] = listmonk.lists()
69
+ list: MailingList = listmonk.list(list_id=7)
70
+
71
+ # Various ways to access existing subscribers
72
+ subscribers: list[] = listmonk.subscribers(list_id=9)
73
+
74
+ subscriber: Subscriber = listmonk.subscriber_by_email('testuser@some.domain')
75
+ subscriber: Subscriber = listmonk.subscriber_by_id(2001)
76
+ subscriber: Subscriber = listmonk.subscriber_by_uuid('f6668cf0-1c...')
77
+
78
+ # Create a new subscriber
79
+ new_subscriber = listmonk.create_subscriber(
80
+ 'testuser@some.domain', 'Jane Doe',
81
+ [1, 7, 9], pre_confirm=True, attribs={...} )
82
+
83
+ # Change the email, custom rating, and add to lists 4 & 6, remove from 5.
84
+ subscriber.email = 'newemail@some.domain'
85
+ subscriber.attribs['rating'] = 7
86
+ updated_subscriber = listmonk.update_subscriber(new_subscriber, {4, 6}, {5})
87
+
88
+ # Disable then re-enable a subscriber
89
+ subscriber = listmonk.disable_subscriber(subscriber)
90
+ subscriber = listmonk.enable_subscriber(subscriber)
91
+
92
+ # Block (unsubscribe) them
93
+ listmonk.block_subscriber(subscriber)
94
+
95
+ # Fully delete them from your system
96
+ listmonk.delete_subscriber(subscriber.email)
97
+
98
+ # Send an individual, transacational email (e.g. password reset)
99
+ to_email = 'testuser@some.domain'
100
+ from_email = 'app@your.domain'
101
+ template_id = 3 # *TX* template ID from listmonk
102
+ template_data = {'full_name': 'Test User', 'reset_code': 'abc123'}
103
+
104
+ status: bool = listmonk.send_transactional_email(
105
+ to_email, template_id, from_email=from_email,
106
+ template_data=template_data, content_type='html')
107
+ ```
108
+
109
+
110
+
111
+ ## Want to contribute?
112
+
113
+ PRs are welcome. Enjoy.
@@ -0,0 +1,88 @@
1
+ # Listmonk Email App API Client for Python
2
+
3
+ Client for the for open source, self-hosted [Listmonk email platform](https://listmonk.app) based on
4
+ [httpx](https://www.python-httpx.org) and [pydantic](https://pydantic.dev).
5
+
6
+ `listmonk` is intended for integrating your Listmonk instance into your web app. The [Listmonk API is extensive](https://listmonk.app/docs/apis/apis/) but this only covers the subset that most developers will need for common SaaS actions such as subscribe, unsubscribe, and segmentate users (into separate lists).
7
+
8
+ So while it doesn't currently cover every endpoint (for example you cannot create a list programatically nor can you edit HTML templates for campaigns over APIs) it will likely work for you. That said, PRs are weclome.
9
+
10
+ 🔀 Async is currently planned but not yet implemented. With the httpx-base, it should be trivial if needed.
11
+
12
+ ## Core Features
13
+
14
+ * ➕**Add a subscriber** to your subscribed users.
15
+ * 🙎 Get **subscriber details** by email, ID, UUID, and more.
16
+ * 📝 **Modify subscriber details** (including custom attribute collection).
17
+ * 🔍 **Search** your users based on app and custom attributes.
18
+ * 🏥 Check the **health and connectivity** of your instance.
19
+ * 👥 Retrieve your **segmentation lists**, list details, and subscribers.
20
+ * 🙅 Unsubscribe and block users who don't want to be contacted further.
21
+ * 💥 Completely delete a subscriber from your instance.
22
+ * 📧 Send transactional email with template data (i.e. password reset emails).
23
+
24
+ ## Installation
25
+
26
+ Just `pip install listmonk`
27
+
28
+
29
+ ## Usage
30
+
31
+ ```python
32
+
33
+ import listmonk
34
+ listmonk.set_url_base('https://yourlistmonkurl.com')
35
+
36
+ listmonk.login('sammyz', '1234')
37
+ valid: bool = listmonk.verify_login()
38
+
39
+ # Is it alive and working?
40
+ up: bool = listmonk.is_healthy()
41
+
42
+ # Read data about your lists
43
+ lists: list[] = listmonk.lists()
44
+ list: MailingList = listmonk.list(list_id=7)
45
+
46
+ # Various ways to access existing subscribers
47
+ subscribers: list[] = listmonk.subscribers(list_id=9)
48
+
49
+ subscriber: Subscriber = listmonk.subscriber_by_email('testuser@some.domain')
50
+ subscriber: Subscriber = listmonk.subscriber_by_id(2001)
51
+ subscriber: Subscriber = listmonk.subscriber_by_uuid('f6668cf0-1c...')
52
+
53
+ # Create a new subscriber
54
+ new_subscriber = listmonk.create_subscriber(
55
+ 'testuser@some.domain', 'Jane Doe',
56
+ [1, 7, 9], pre_confirm=True, attribs={...} )
57
+
58
+ # Change the email, custom rating, and add to lists 4 & 6, remove from 5.
59
+ subscriber.email = 'newemail@some.domain'
60
+ subscriber.attribs['rating'] = 7
61
+ updated_subscriber = listmonk.update_subscriber(new_subscriber, {4, 6}, {5})
62
+
63
+ # Disable then re-enable a subscriber
64
+ subscriber = listmonk.disable_subscriber(subscriber)
65
+ subscriber = listmonk.enable_subscriber(subscriber)
66
+
67
+ # Block (unsubscribe) them
68
+ listmonk.block_subscriber(subscriber)
69
+
70
+ # Fully delete them from your system
71
+ listmonk.delete_subscriber(subscriber.email)
72
+
73
+ # Send an individual, transacational email (e.g. password reset)
74
+ to_email = 'testuser@some.domain'
75
+ from_email = 'app@your.domain'
76
+ template_id = 3 # *TX* template ID from listmonk
77
+ template_data = {'full_name': 'Test User', 'reset_code': 'abc123'}
78
+
79
+ status: bool = listmonk.send_transactional_email(
80
+ to_email, template_id, from_email=from_email,
81
+ template_data=template_data, content_type='html')
82
+ ```
83
+
84
+
85
+
86
+ ## Want to contribute?
87
+
88
+ PRs are welcome. Enjoy.
Binary file
@@ -0,0 +1,26 @@
1
+ from listmonk import impl
2
+ from listmonk import models # noqa: F401, E402
3
+ from listmonk.impl import create_subscriber, delete_subscriber, update_subscriber # noqa: F401, E402
4
+ from listmonk.impl import disable_subscriber, enable_subscriber, block_subscriber # noqa: F401, E402
5
+ from listmonk.impl import is_healthy # noqa: F401, E402
6
+ from listmonk.impl import lists, list_by_id # noqa: F401, E402
7
+ from listmonk.impl import login, verify_login # noqa: F401, E402
8
+ from listmonk.impl import send_transactional_email # noqa: F401, E402
9
+ from listmonk.impl import set_url_base, get_base_url # noqa: F401, E402
10
+ from listmonk.impl import subscribers, subscriber_by_email, subscriber_by_id, subscriber_by_uuid # noqa: F401, E402
11
+
12
+ __author__ = 'Michael Kennedy <michael@talkpython.fm>'
13
+ __version__ = impl.__version__
14
+ user_agent = impl.user_agent
15
+
16
+ __all__ = [
17
+ models,
18
+ login, verify_login,
19
+ set_url_base, get_base_url,
20
+ lists, list_by_id,
21
+ subscribers, subscriber_by_email, subscriber_by_id, subscriber_by_uuid,
22
+ create_subscriber, delete_subscriber, update_subscriber,
23
+ disable_subscriber, enable_subscriber, block_subscriber,
24
+ send_transactional_email,
25
+ is_healthy,
26
+ ]
Binary file
@@ -0,0 +1,416 @@
1
+ import sys
2
+ import urllib.parse
3
+ from base64 import b64encode
4
+ from typing import Optional, Tuple
5
+
6
+ import httpx
7
+
8
+ from listmonk import models, urls # noqa: F401
9
+
10
+ __version__ = '0.1.0'
11
+
12
+ from listmonk.models import SubscriberStatuses
13
+
14
+ # region global vars
15
+ url_base: Optional[str] = None
16
+ username: Optional[str] = None
17
+ password: Optional[str] = None
18
+
19
+ user_agent = (f'Listmonk-Client v{__version__} / '
20
+ f'Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro} / '
21
+ f'{sys.platform.capitalize()}')
22
+
23
+ core_headers: dict[str, Optional[str]] = {
24
+ 'Authorization': None, # Set at login
25
+ 'Content-Type': 'application/json',
26
+ 'User-Agent': user_agent,
27
+ }
28
+
29
+
30
+ # endregion
31
+
32
+ # region def get_base_url() -> Optional[str]
33
+
34
+ def get_base_url() -> Optional[str]:
35
+ return url_base
36
+
37
+
38
+ # endregion
39
+
40
+ # region def set_url_base(url: str)
41
+
42
+ def set_url_base(url: str):
43
+ if not url or not url.strip():
44
+ raise Exception("URL must not be empty")
45
+
46
+ global url_base
47
+ url_base = url.strip()
48
+
49
+
50
+ # endregion
51
+
52
+ # region def login(user_name: str, pw: str)
53
+
54
+ def login(user_name: str, pw: str):
55
+ global core_headers, username, password
56
+
57
+ validate_login(user_name, pw)
58
+ username = user_name
59
+ password = pw
60
+
61
+ user_pass = f'{user_name}:{pw}'.encode()
62
+ user_pass_encoded = b64encode(user_pass).decode()
63
+
64
+ core_headers['Authorization'] = f'Basic {user_pass_encoded}'
65
+ if not verify_login():
66
+ core_headers['Authorization'] = None
67
+ return False
68
+
69
+ return True
70
+
71
+
72
+ # endregion
73
+
74
+ # region def lists() -> list[models.MailingList]
75
+
76
+ def lists() -> list[models.MailingList]:
77
+ global core_headers
78
+ validate_state(url=True, user=True)
79
+
80
+ url = f'{url_base}{urls.lists}?page=1&per_page=1000000'
81
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
82
+ resp.raise_for_status()
83
+
84
+ data = resp.json()
85
+ list_of_lists = [models.MailingList(**d) for d in data.get('data', {}).get('results', [])]
86
+ return list_of_lists
87
+
88
+
89
+ # endregion
90
+
91
+ # region def list_by_id(list_id: int) -> Optional[models.MailingList]
92
+
93
+ def list_by_id(list_id: int) -> Optional[models.MailingList]:
94
+ global core_headers
95
+ validate_state(url=True, user=True)
96
+
97
+ url = f'{url_base}{urls.lst}'
98
+ url = url.format(list_id=list_id)
99
+
100
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True, timeout=30)
101
+ resp.raise_for_status()
102
+
103
+ data = resp.json()
104
+ lst_data = data.get('data')
105
+ return models.MailingList(**lst_data)
106
+
107
+
108
+ # endregion
109
+
110
+ # region def subscribers(query_text: Optional[str] = None, list_id: Optional[int] = None) -> list[models.Subscriber]
111
+
112
+ def subscribers(query_text: Optional[str] = None, list_id: Optional[int] = None) -> list[models.Subscriber]:
113
+ global core_headers
114
+ validate_state(url=True, user=True)
115
+
116
+ raw_results = []
117
+ page_num = 1
118
+ partial_results, more = _fragment_of_subscribers(page_num, list_id, query_text)
119
+ raw_results.extend(partial_results)
120
+ print(f"subscribers(): Got {len(raw_results)} so far, more? {more}")
121
+ while more:
122
+ page_num += 1
123
+ partial_results, more = _fragment_of_subscribers(page_num, list_id, query_text)
124
+ raw_results.extend(partial_results)
125
+ print(f"subscribers(): Got {len(raw_results)} so far on page {page_num}, more? {more}")
126
+
127
+ subscriber_list = [models.Subscriber(**d) for d in raw_results]
128
+
129
+ return subscriber_list
130
+
131
+
132
+ # endregion
133
+
134
+ # region def _fragment_of_subscribers(page_num: int, list_id: Optional[int], query_text: Optional[str])
135
+
136
+ def _fragment_of_subscribers(page_num: int, list_id: Optional[int], query_text: Optional[str]) \
137
+ -> Tuple[list[dict], bool]:
138
+ """
139
+ Returns:
140
+ Tuple of partial_results, more_to_retrieve
141
+ """
142
+ per_page = 500
143
+
144
+ url = f'{url_base}{urls.subscribers}?page={page_num}&per_page={per_page}&order_by=updated_at&order=DESC'
145
+
146
+ if list_id:
147
+ url += f'&list_id={list_id}'
148
+
149
+ if query_text:
150
+ url += f"&query={urllib.parse.urlencode({'query': query_text})}"
151
+
152
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
153
+ resp.raise_for_status()
154
+
155
+ # For paging:
156
+ # data: {"total":55712,"per_page":10,"page":1, ...}
157
+ raw_data = resp.json()
158
+ data = raw_data['data']
159
+
160
+ total = data.get('total', 0)
161
+ retrieved = per_page * page_num
162
+ more = retrieved < total
163
+
164
+ local_results = data.get('results', [])
165
+ return local_results, more
166
+
167
+
168
+ # endregion
169
+
170
+ # region def subscriber_by_email(email: str) -> Optional[models.Subscriber]
171
+
172
+ def subscriber_by_email(email: str) -> Optional[models.Subscriber]:
173
+ global core_headers
174
+ validate_state(url=True, user=True)
175
+
176
+ url = f"{url_base}{urls.subscribers}?page=1&per_page=100&query=subscribers.email='{email}'"
177
+
178
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
179
+ resp.raise_for_status()
180
+
181
+ raw_data = resp.json()
182
+ results: list[dict] = raw_data['data']['results']
183
+
184
+ if not results:
185
+ return None
186
+
187
+ return models.Subscriber(**results[0])
188
+
189
+
190
+ # endregion
191
+
192
+ # region def subscriber_by_id(subscriber_id: int) -> Optional[models.Subscriber]
193
+
194
+ def subscriber_by_id(subscriber_id: int) -> Optional[models.Subscriber]:
195
+ global core_headers
196
+ validate_state(url=True, user=True)
197
+
198
+ url = f"{url_base}{urls.subscribers}?page=1&per_page=100&query=subscribers.id={subscriber_id}"
199
+
200
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
201
+ resp.raise_for_status()
202
+
203
+ raw_data = resp.json()
204
+ results: list[dict] = raw_data['data']['results']
205
+
206
+ if not results:
207
+ return None
208
+
209
+ return models.Subscriber(**results[0])
210
+
211
+
212
+ # endregion
213
+
214
+ # region subscriber_by_uuid(subscriber_uuid: str) -> Optional[models.Subscriber]
215
+
216
+ def subscriber_by_uuid(subscriber_uuid: str) -> Optional[models.Subscriber]:
217
+ global core_headers
218
+ validate_state(url=True, user=True)
219
+
220
+ url = f"{url_base}{urls.subscribers}?page=1&per_page=100&query=subscribers.uuid='{subscriber_uuid}'"
221
+
222
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
223
+ resp.raise_for_status()
224
+
225
+ raw_data = resp.json()
226
+ results: list[dict] = raw_data['data']['results']
227
+
228
+ if not results:
229
+ return None
230
+
231
+ return models.Subscriber(**results[0])
232
+
233
+
234
+ # endregion
235
+
236
+ # region def create_subscriber(email: str, name: str, list_ids: list[int], pre_confirm: bool, attribs: dict)
237
+ # -> models.Subscriber
238
+
239
+ def create_subscriber(email: str, name: str, list_ids: list[int],
240
+ pre_confirm: bool, attribs: dict) -> models.Subscriber:
241
+ global core_headers
242
+ validate_state(url=True, user=True)
243
+ email = (email or '').lower().strip()
244
+ name = (name or '').strip()
245
+ if not email:
246
+ raise ValueError("Email is required")
247
+ if not name:
248
+ raise ValueError("Name is required")
249
+
250
+ model = models.CreateSubscriberModel(email=email, name=name, status='enabled', lists=list_ids,
251
+ preconfirm_subscriptions=pre_confirm, attribs=attribs)
252
+
253
+ url = f"{url_base}{urls.subscribers}"
254
+ resp = httpx.post(url, json=model.model_dump(), headers=core_headers, follow_redirects=True)
255
+ resp.raise_for_status()
256
+
257
+ raw_data = resp.json()
258
+ # pprint(raw_data)
259
+ sub_data = raw_data['data']
260
+ return models.Subscriber(**sub_data)
261
+
262
+
263
+ # endregion
264
+
265
+ # region def delete_subscriber(email: Optional[str] = None, overriding_subscriber_id: Optional[int] = None) -> bool
266
+
267
+ def delete_subscriber(email: Optional[str] = None, overriding_subscriber_id: Optional[int] = None) -> bool:
268
+ global core_headers
269
+ validate_state(url=True, user=True)
270
+ email = (email or '').lower().strip()
271
+ if not email and not overriding_subscriber_id:
272
+ raise ValueError("Email is required")
273
+
274
+ subscriber_id = overriding_subscriber_id
275
+ if not subscriber_id:
276
+ subscriber = subscriber_by_email(email)
277
+ if not subscriber:
278
+ return False
279
+ subscriber_id = subscriber.id
280
+
281
+ url = f"{url_base}{urls.subscriber.format(subscriber_id=subscriber_id)}"
282
+ resp = httpx.delete(url, headers=core_headers, follow_redirects=True)
283
+ resp.raise_for_status()
284
+
285
+ raw_data = resp.json()
286
+ return raw_data.get('data') # {'data': True}
287
+
288
+
289
+ # endregion
290
+
291
+ # region def update_subscriber(subscriber: models.Subscriber, add_to_lists: set[int], remove_from_lists: set[int])
292
+
293
+ def update_subscriber(subscriber: models.Subscriber, add_to_lists: set[int] = None, remove_from_lists: set[int] = None,
294
+ status: SubscriberStatuses = SubscriberStatuses.enabled) -> models.Subscriber:
295
+ global core_headers
296
+ validate_state(url=True, user=True)
297
+ if subscriber is None or not subscriber.id:
298
+ raise ValueError("Subscriber is required")
299
+
300
+ add_to_lists = add_to_lists or set()
301
+ remove_from_lists = remove_from_lists or set()
302
+
303
+ existing_lists = set([int(lst.get('id')) for lst in subscriber.lists])
304
+ final_lists = (existing_lists - remove_from_lists)
305
+ final_lists.update(add_to_lists)
306
+
307
+ update_model = models.CreateSubscriberModel(
308
+ email=subscriber.email,
309
+ name=subscriber.name,
310
+ status=status,
311
+ lists=list(final_lists),
312
+ preconfirm_subscriptions=True,
313
+ attribs=subscriber.attribs
314
+ )
315
+
316
+ url = f"{url_base}{urls.subscriber.format(subscriber_id=subscriber.id)}"
317
+ resp = httpx.put(url, json=update_model.model_dump(), headers=core_headers, follow_redirects=True)
318
+ resp.raise_for_status()
319
+
320
+ return subscriber_by_id(subscriber.id)
321
+
322
+
323
+ # endregion
324
+
325
+ def disable_subscriber(subscriber: models.Subscriber) -> models.Subscriber:
326
+ return update_subscriber(subscriber, status=SubscriberStatuses.disabled)
327
+
328
+
329
+ def enable_subscriber(subscriber: models.Subscriber) -> models.Subscriber:
330
+ return update_subscriber(subscriber, status=SubscriberStatuses.enabled)
331
+
332
+
333
+ def block_subscriber(subscriber: models.Subscriber) -> models.Subscriber:
334
+ return update_subscriber(subscriber, status=SubscriberStatuses.blocklisted)
335
+
336
+
337
+ # region def delete_subscriber(email: Optional[str] = None, overriding_subscriber_id: Optional[int] = None) -> bool
338
+
339
+ def send_transactional_email(subscriber_email: str, template_id: int, from_email: str, template_data: dict,
340
+ messenger_channel: str = 'email', content_type: str = 'markdown') -> bool:
341
+ global core_headers
342
+ validate_state(url=True, user=True)
343
+ subscriber_email = (subscriber_email or '').lower().strip()
344
+ if not subscriber_email:
345
+ raise ValueError("Email is required")
346
+
347
+ body_data = {
348
+ 'subscriber_email': subscriber_email,
349
+ 'from_email': from_email,
350
+ 'template_id': template_id,
351
+ 'data': template_data,
352
+ 'messenger': messenger_channel,
353
+ 'content_type': content_type,
354
+ }
355
+ try:
356
+ url = f"{url_base}{urls.send_tx}"
357
+ resp = httpx.post(url, json=body_data, headers=core_headers, follow_redirects=True)
358
+ resp.raise_for_status()
359
+
360
+ raw_data = resp.json()
361
+ return raw_data.get('data') # {'data': True}
362
+ except Exception as e:
363
+ # print(e)
364
+ # print(resp.text)
365
+ raise
366
+
367
+ # endregion
368
+
369
+
370
+ # region def is_healthy() -> bool
371
+
372
+ def is_healthy() -> bool:
373
+ # noinspection PyBroadException
374
+ try:
375
+ validate_state(url=True, user=True)
376
+
377
+ url = f'{url_base}{urls.health}'
378
+ resp = httpx.get(url, headers=core_headers, follow_redirects=True)
379
+ resp.raise_for_status()
380
+
381
+ data = resp.json()
382
+ return data.get('data', False)
383
+ except Exception:
384
+ return False
385
+
386
+
387
+ # endregion
388
+
389
+ # region def verify_login() -> bool
390
+ def verify_login() -> bool:
391
+ return is_healthy()
392
+
393
+
394
+ # endregion
395
+
396
+ # region def validate_login(user_name, pw)
397
+
398
+ def validate_login(user_name, pw):
399
+ if not user_name:
400
+ raise Exception("Username cannot be empty")
401
+ if not pw:
402
+ raise Exception("Password cannot be empty")
403
+
404
+
405
+ # endregion
406
+
407
+ # region def validate_state(url=False, user=False)
408
+
409
+ def validate_state(url=False, user=False):
410
+ if url and not url_base:
411
+ raise Exception("URL Base must be set to proceed.")
412
+
413
+ if user and core_headers.get('Authorization') is None:
414
+ raise Exception("You must login before proceeding.")
415
+
416
+ # endregion
Binary file
@@ -0,0 +1,56 @@
1
+ import datetime
2
+ import enum
3
+ import typing
4
+
5
+ import pydantic
6
+ from pydantic import BaseModel, field_serializer
7
+
8
+
9
+ class SubscriberStatuses(enum.StrEnum):
10
+ enabled = "enabled"
11
+ disabled = "disabled"
12
+ blocklisted = "blocklisted"
13
+
14
+
15
+ class SubscriberStatus(BaseModel):
16
+ unconfirmed_count: int = pydantic.Field(alias="unconfirmed")
17
+
18
+
19
+ class MailingList(BaseModel):
20
+ id: int
21
+ created_at: datetime.datetime
22
+ updated_at: datetime.datetime
23
+ uuid: str
24
+ name: str
25
+ type: str
26
+ optin: str
27
+ tags: list[str]
28
+ description: str
29
+ subscriber_count: int
30
+ subscriber_statuses: SubscriberStatus
31
+
32
+
33
+ class Subscriber(BaseModel):
34
+ id: int
35
+ email: str
36
+ name: str
37
+ created_at: datetime.datetime
38
+ updated_at: datetime.datetime
39
+ uuid: typing.Optional[str] = None
40
+ lists: list[dict] = []
41
+ attribs: dict[str, typing.Any] = {}
42
+ status: typing.Optional[str] = None
43
+
44
+ @field_serializer('created_at', 'updated_at')
45
+ def serialize_date_times(self, fld: datetime, _info):
46
+ formatted_string = fld.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
47
+ return formatted_string
48
+
49
+
50
+ class CreateSubscriberModel(BaseModel):
51
+ email: str
52
+ name: str
53
+ status: str
54
+ lists: list[int] = []
55
+ preconfirm_subscriptions: bool
56
+ attribs: dict = {}
@@ -0,0 +1,6 @@
1
+ health = '/api/health'
2
+ lists = '/api/lists'
3
+ lst = '/api/lists/{list_id}'
4
+ subscriber = '/api/subscribers/{subscriber_id}'
5
+ subscribers = '/api/subscribers'
6
+ send_tx = '/api/tx'
@@ -0,0 +1,59 @@
1
+ [project]
2
+ name = "listmonk"
3
+ description = "Listmonk Email App API Client for Python"
4
+ readme = "README.md"
5
+ license = "MIT"
6
+ requires-python = ">=3.8"
7
+ keywords = [
8
+ "email",
9
+ "newsletters",
10
+ "marketing",
11
+ "api-client",
12
+ ]
13
+ authors = [
14
+ { name = "Michael Kennedy", email = "michael@talkpython.fm" },
15
+ ]
16
+ classifiers = [
17
+ 'Development Status :: 2 - Pre-Alpha',
18
+ 'License :: OSI Approved :: MIT License',
19
+ 'Programming Language :: Python',
20
+ 'Programming Language :: Python :: 3',
21
+ 'Programming Language :: Python :: 3.8',
22
+ 'Programming Language :: Python :: 3.9',
23
+ 'Programming Language :: Python :: 3.10',
24
+ 'Programming Language :: Python :: 3.11',
25
+ 'Programming Language :: Python :: 3.12',
26
+ ]
27
+ dependencies = [
28
+ "httpx",
29
+ "pydantic",
30
+ ]
31
+ version = "0.1.0"
32
+
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/mikeckennedy/listmonk"
36
+ Tracker = "https://github.com/mikeckennedy/listmonk/issues"
37
+ Source = "https://github.com/mikeckennedy/listmonk"
38
+
39
+ [build-system]
40
+ requires = ["hatchling>=1.21.0", "hatch-vcs>=0.3.0"]
41
+ build-backend = "hatchling.build"
42
+
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ exclude = [
46
+ "/.github",
47
+ "/tests",
48
+ "/example_client",
49
+ "settings.json",
50
+ ]
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["listmonk"]
54
+ exclude = [
55
+ "/.github",
56
+ "/tests",
57
+ "/example_client",
58
+ "settings.json",
59
+ ]