nacwrap 0.1.0__py3-none-any.whl

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.
nacwrap/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .nacwrap import *
nacwrap/nacwrap.py ADDED
@@ -0,0 +1,197 @@
1
+ """
2
+ This module contains functions to interact with the Nintex Workflow Cloud API.
3
+ """
4
+
5
+ import json
6
+ import os
7
+ from datetime import datetime
8
+ from typing import Literal, Optional, Union
9
+
10
+ import requests
11
+
12
+
13
+ class Decorators:
14
+ """
15
+ Decorators class
16
+ """
17
+
18
+ @staticmethod
19
+ def refresh_token(decorated):
20
+ """
21
+ Decorator to refresh the access token if it has expired or generate
22
+ a new one if it does not exist.
23
+ """
24
+
25
+ def wrapper(*args, **kwargs):
26
+ """
27
+ Wrapper function
28
+ Args:
29
+ *args:
30
+ **kwargs:
31
+
32
+ Returns:
33
+ decorated function
34
+ """
35
+ if "NTX_BEARER_TOKEN_EXPIRES_AT" not in os.environ:
36
+ expires_at = "01/01/1901 00:00:00"
37
+ else:
38
+ expires_at = os.environ["NTX_BEARER_TOKEN_EXPIRES_AT"]
39
+ if (
40
+ "NTX_BEARER_TOKEN" not in os.environ
41
+ or datetime.strptime(expires_at, "%m/%d/%Y %H:%M:%S") < datetime.now()
42
+ ):
43
+ Decorators.get_token()
44
+ return decorated(*args, **kwargs)
45
+
46
+ wrapper.__name__ = decorated.__name__
47
+ return wrapper
48
+
49
+ @staticmethod
50
+ def get_token():
51
+ """
52
+ Get Nintex bearer token
53
+ """
54
+ if "NINTEX_BASE_URL" not in os.environ:
55
+ raise Exception("NINTEX_BASE_URL not set in environment")
56
+ if "NINTEX_CLIENT_ID" not in os.environ:
57
+ raise Exception("NINTEX_CLIENT_ID not set in environment")
58
+ if "NINTEX_CLIENT_SECRET" not in os.environ:
59
+ raise Exception("NINTEX_CLIENT_SECRET not set in environment")
60
+ if "NINTEX_GRANT_TYPE" not in os.environ:
61
+ raise Exception("NINTEX_GRANT_TYPE not set in environment")
62
+
63
+ headers = {
64
+ "Accept": "application/json",
65
+ "Content-Type": "application/x-www-form-urlencoded",
66
+ }
67
+ response = requests.post(
68
+ os.environ["NINTEX_BASE_URL"] + "/authentication/v1/token",
69
+ headers=headers,
70
+ data={
71
+ "client_id": os.environ["NINTEX_CLIENT_ID"],
72
+ "client_secret": os.environ["NINTEX_CLIENT_SECRET"],
73
+ "grant_type": os.environ["NINTEX_GRANT_TYPE"],
74
+ },
75
+ timeout=30,
76
+ )
77
+ try:
78
+ os.environ["NTX_BEARER_TOKEN"] = response.json()["access_token"]
79
+ except Exception as e:
80
+ print("Error, could not set OS env bearer token: ", e)
81
+ print(response.content)
82
+ raise Exception("Error, could not set OS env bearer token: ", e)
83
+ try:
84
+ os.environ["NTX_EXPIRES_AT"] = response.json()["expires_at"]
85
+ except Exception as e:
86
+ print("Error, could not set os env expires at: ", e)
87
+ raise Exception("Error, could not set os env expires at: ", e)
88
+
89
+
90
+ @Decorators.refresh_token
91
+ def create_instance(workflow_id: str, start_data: Optional[dict] = None) -> dict:
92
+ """
93
+ Creates a Nintex workflow instance for a given workflow.
94
+ If successful, returns response which should be a dict containing
95
+ instance ID that was created.
96
+ """
97
+ if "NINTEX_BASE_URL" not in os.environ:
98
+ raise Exception("NINTEX_BASE_URL not set in environment")
99
+ if start_data is None:
100
+ print("No start data provided")
101
+ start_data = {}
102
+ try:
103
+ data = json.dumps({"startData": start_data})
104
+ print(data)
105
+ response = requests.post(
106
+ os.environ["NINTEX_BASE_URL"]
107
+ + "/workflows/v1/designs/"
108
+ + workflow_id
109
+ + "/instances",
110
+ headers={
111
+ "Authorization": "Bearer " + os.environ["NTX_BEARER_TOKEN"],
112
+ "Content-Type": "application/json",
113
+ },
114
+ data=data,
115
+ timeout=30,
116
+ )
117
+ response.raise_for_status()
118
+ except requests.exceptions.RequestException as e:
119
+ print(f"Error creating instance for {start_data}: {e}")
120
+ raise Exception(f"Error creating instance for {start_data}: {e}")
121
+ if response.status_code != 202:
122
+ print(f"Error creating instance for {start_data}")
123
+ print(response.content)
124
+ raise Exception(f"Error creating instance for {start_data}")
125
+
126
+ return response.json()
127
+
128
+
129
+ @Decorators.refresh_token
130
+ def get_instance_data(
131
+ workflow_name: Optional[str] = None,
132
+ status: Optional[str] = None,
133
+ order_by: Union[Literal["ASC", "DESC"], None] = None,
134
+ from_datetime: Optional[datetime] = None,
135
+ to_datetime: Optional[datetime] = None,
136
+ page_size: Optional[int] = 100,
137
+ ) -> list[dict]:
138
+ """
139
+ Get Nintex instance data Follows nextLink until no more pages.
140
+ Function goes through all instance data in Nintex.
141
+
142
+ - workflow_name: Name of the workflow to filter by
143
+ - status: Status of the workflow to filter by
144
+ - order_by: Order of the results
145
+ - from_datetime: Start date to filter by
146
+ - to_datetime: End date to filter by
147
+ - page_size: Number of results per page
148
+
149
+ Note: If from_datetime and to_datetime are not provided, the Nintex API
150
+ defaults to returning the last 30 days. If you want everything, you need to
151
+ explicitly use some sufficiently large time range.
152
+ """
153
+ base_url = os.environ["NINTEX_BASE_URL"] + "/workflows/v2/instances"
154
+ params = {
155
+ "workflowName": workflow_name,
156
+ "status": status,
157
+ "order": order_by,
158
+ "from": (
159
+ from_datetime.strftime("%Y-%m-%dT%H:%M:%S.%fZ") if from_datetime else None
160
+ ),
161
+ "to": to_datetime.strftime("%Y-%m-%dT%H:%M:%S.%fZ") if to_datetime else None,
162
+ "pageSize": page_size,
163
+ }
164
+
165
+ # Remove None values
166
+ params = {k: v for k, v in params.items() if v is not None}
167
+
168
+ results = []
169
+ url = base_url
170
+ first_request = True
171
+
172
+ while url:
173
+ # If this is subsequent requests, don't need to pass params
174
+ # will be provided in the skip URL
175
+ if first_request:
176
+ first_request = False
177
+ else:
178
+ params = None
179
+
180
+ response = requests.get(
181
+ url,
182
+ headers={
183
+ "Authorization": "Bearer " + os.environ["NTX_BEARER_TOKEN"],
184
+ "Content-Type": "application/json",
185
+ },
186
+ params=params,
187
+ timeout=30,
188
+ )
189
+ pass
190
+ if response.status_code == 200:
191
+ data = response.json()
192
+ results += data["instances"]
193
+ url = data.get("nextLink")
194
+ else:
195
+ print("Error, could not get instance data: ", response.content)
196
+ break
197
+ return results
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.1
2
+ Name: nacwrap
3
+ Version: 0.1.0
4
+ Summary: Python package that acts as a wrapper for the Nintex Automation Cloud system.
5
+ Home-page: https://github.com/pepsimidamerica/nacwrap
6
+ Author: Jordan Maynor
7
+ Author-email: jmaynor@pepsimidamerica.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.12
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests
15
+
16
+ # Overview
17
+
18
+ nacwrap is a python package for interacting with the Nintex Automation Cloud system. Creating workflow instances, delegating tasks, etc. Essentially just a wrapper for the NAC API.
19
+
20
+ ## Installation
21
+
22
+ Haven't yet bothered to publish as a python package, intent is to simply add nacwrap as a git submodule in any projects where it's needed.
23
+
24
+ ## Usage
25
+
26
+ Several environment variables are required for nacwrap to function.
27
+
28
+ | Required? | Env Variable | Description |
29
+ | --------- | ------------ | ----------- |
30
+ | Yes | NINTEX_CLIENT_ID | Client ID for connecting to Nintex API. Created in Apps and Tokens page in NAC. |
31
+ | Yes | NINTEX_CLIENT_SECRET | Client secret for connecting to Nintex API. Created in Apps and Tokens page in NAC. |
32
+ | Yes | NINTEX_GRANT_TYPE | Value should be 'client_credentials'. |
33
+ | Yes | NINTEX_BASE_URL | Value depends on which Nintex region you are in. US is, for example 'us.nintex.io'. <https://developer.nintex.com/docs/nc-api-docs/d2924cfeea6e8-welcome-to-the-nintex-automation-cloud-api#choose-your-region> |
34
+
35
+ ### Instances - Create Instance
36
+
37
+ Function to create a workflow instance. Takes in two parameters.
38
+
39
+ workflow_id: The ID of the workflow you want to create an instance for.
40
+
41
+ start_data: Optional, any start data the worklfow requires. Should be provided in dictionary format. Returns JSON response if successful.
42
+
43
+ ### Instances - List Instances
44
+
45
+ Function to return instance data. Takes a number of parameters for filtering what instance data to get.
46
+
47
+ ### Tasks - Delegate Assignment (TODO)
48
+
49
+ Make function to delegate tasks from one user to another.
@@ -0,0 +1,7 @@
1
+ nacwrap/__init__.py,sha256=nbY1GQQYpCk542qaG5d6z7122v8Ehz6xwJ-iNOYtUF4,24
2
+ nacwrap/nacwrap.py,sha256=kU9XG1Gt0oLjNqwwZl1f11GMA-q5T_oIGQn0-j9FySw,6818
3
+ nacwrap-0.1.0.dist-info/LICENSE,sha256=KrPIO2Ij3T_47dfpfngKzpC4EXohIZMsHauG0R4M-kM,1234
4
+ nacwrap-0.1.0.dist-info/METADATA,sha256=VMHox1Oic5BbeQ4DtLfjfqiJJMkzV5z_gEFSu6doZjo,2169
5
+ nacwrap-0.1.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
6
+ nacwrap-0.1.0.dist-info/top_level.txt,sha256=rKgaT4NCL0BkuNmJ_KQjJ_vw-RLQikqmHRfGcpjoYDQ,8
7
+ nacwrap-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ nacwrap