-
Notifications
You must be signed in to change notification settings - Fork 0
/
pandaworkspace.py
222 lines (185 loc) · 7.76 KB
/
pandaworkspace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""pandaworkspace.py implements API Wrapper for Workspaces https://developers.pandadoc.com/reference#about"""
__author__ = "Kostyantyn Ovechko"
__copyright__ = "Copyright 2020, Zxscript"
__license__ = "MIT"
__version__ = "0.0.1"
__email__ = "kos@zxscript.com"
__status__ = "Production"
import os
import string
import random
import requests
from .panda_exceptions import ApiException
from .request_limit_manager import SleepRequestLimitManager
from .pandadocument import PandaDocumentAbstract
from .pandafolder import PandaFolder
from .pandatemplate import PandaTemplateAbstract
DEFAULT_PANDAWORKSPACE_API_KEY = os.environ.get('DEFAULT_PANDAWORKSPACE_API_KEY', 'put-your-key-here')
DEFAULT_PANDADOC_BASE_API_URL = os.environ.get('DEFAULT_PANDADOC_BASE_API_URL', 'https://api.pandadoc.com/public/v1/')
DEFAULT_PANDADOC_BASE_APP_URL = os.environ.get('DEFAULT_PANDADOC_BASE_APP_URL', 'https://app.pandadoc.com/')
DEFAULT_PANDADOC_DOWNLOAD_FOLDER = os.environ.get('DEFAULT_PANDADOC_DOWNLOAD_FOLDER', './pandadoc_docs')
DEFAULT_RANDOM_FILENAME_LENGTH = int(os.environ.get('DEFAULT_RANDOM_FILENAME_LENGTH', '20'))
API_RESPONSE_SUCCESSFUL_STATUS_CODES = {200, 201, 204}
class PandaWorkspace:
def __init__(self, request_limit_manager=SleepRequestLimitManager):
self.__api_key = DEFAULT_PANDAWORKSPACE_API_KEY
self.__base_api_url = DEFAULT_PANDADOC_BASE_API_URL
self.__base_app_url = DEFAULT_PANDADOC_BASE_APP_URL
self.__download_folder = DEFAULT_PANDADOC_DOWNLOAD_FOLDER
self.__random_filename_length = DEFAULT_RANDOM_FILENAME_LENGTH
self.__request_limit_manager = request_limit_manager
@property
def documents(self):
class __PandaDocument(PandaDocumentAbstract):
_pandaworkspace = self
return __PandaDocument
@property
def templates(self):
class __PandaTemplate(PandaTemplateAbstract):
_pandaworkspace = self
return __PandaTemplate
@property
def tempate_folders(self):
class __PandaTemplatesFolder(PandaFolder):
_pandaworkspace = self
@classmethod
def get_folder_type(cls):
return 'templates'
return __PandaTemplatesFolder
@property
def document_folders(self):
class __PandaDocumentsFolder(PandaFolder):
_pandaworkspace = self
@classmethod
def get_folder_type(cls):
return 'documents'
return __PandaDocumentsFolder
@property
def random_filename_length(self):
return self.__random_filename_length
@random_filename_length.setter
def random_filename_length(self, value):
self.__random_filename_length = value
@property
def headers(self):
return {
'Authorization': 'API-Key {api_key}'.format(api_key=self.__api_key),
# 'Authorization': 'Bearer 755eafd4eb987e3aa2d8cc9f3f0b9b2220dc6959',
'Content-Type': 'application/json',
}
@property
def api_key(self):
return self.__api_key
@api_key.setter
def api_key(self, value):
self.__api_key = value
@property
def base_api_url(self):
return self.__base_api_url
@base_api_url.setter
def base_api_url(self, value):
self.__base_api_url = value
def get_api_url(self, uri):
return '{base_url}{uri}'.format(base_url=self.base_api_url, uri=uri)
@property
def base_app_url(self):
return self.__base_app_url
@base_app_url.setter
def base_app_url(self, value):
self.__base_app_url = value
def get_app_url(self, uri):
return '{base_url}{uri}'.format(base_url=self.base_app_url, uri=uri)
@property
def download_folder(self):
return self.__download_folder
@download_folder.setter
def download_folder(self, value):
self.__download_folder = value
def random_filepath(self, download_folder: str = None, ext: str = '.pdf'):
letters = string.digits + string.ascii_letters
if download_folder is None:
download_folder = self.__download_folder
while True:
filename = ''.join(random.choice(letters) for i in range(self.random_filename_length))
filename_with_ext = '{filename}{ext}'.format(
filename=filename,
ext=ext,
)
filepath = os.path.join(download_folder, filename_with_ext)
if not os.path.isfile(filepath):
break
return filepath
@staticmethod
def debug_response(response):
print(response.status_code)
print(response.text)
@classmethod
def check_response(cls, response, debug=False):
if debug:
cls.debug_response(response)
if response.status_code not in API_RESPONSE_SUCCESSFUL_STATUS_CODES:
raise ApiException(response.text)
def get(self, uri, data=None, debug=False, **kwargs):
# print("=================> ", "GET uri: /", uri)
url = self.get_api_url(uri)
if data is None:
data = {}
with self.__request_limit_manager():
response = requests.get(url, params=data, headers=self.headers, **kwargs)
self.__class__.check_response(response, debug)
return response
def post(self, uri, data=None, debug=True):
# print("=================> ", "POST uri: /", uri)
url = self.get_api_url(uri)
if data is None:
data = {}
with self.__request_limit_manager():
response = requests.post(url, json=data, headers=self.headers)
self.__class__.check_response(response, debug)
return response
def put(self, uri, data=None, debug=False):
# print("=================> ", "PUT uri: /", uri)
url = self.get_api_url(uri)
if data is None:
data = {}
with self.__request_limit_manager():
response = requests.put(url, json=data, headers=self.headers)
self.__class__.check_response(response, debug)
return response
def delete(self, uri, data=None, debug=False):
# print("=================> ", "DELETE uri: /", uri)
url = self.get_api_url(uri)
if data is None:
data = {}
with self.__request_limit_manager():
response = requests.delete(url, data=data, headers=self.headers)
self.__class__.check_response(response, debug)
return response
def download(self, uri, filename=None, download_folder=None, debug=False) -> str:
with self.__request_limit_manager(max_attempts=5, retry_delay=60, for_download=True):
response = self.get(uri, debug=False)
self.__class__.check_response(response, debug)
if download_folder is None:
download_folder = self.download_folder
if filename is None:
filepath = self.random_filepath(download_folder)
else:
filepath = os.path.join(download_folder, filename)
with open(filepath, 'wb') as f:
f.write(response.content)
return filepath
def download_large(self, uri, filename=None, download_folder=None, debug=False) -> str:
if download_folder is None:
download_folder = self.download_folder
if filename is None:
filepath = self.random_filepath(download_folder)
else:
filepath = os.path.join(download_folder, filename)
with self.__request_limit_manager(max_attempts=5, retry_delay=60, for_download=True):
with self.get(uri, debug=False, stream=True) as response:
self.__class__.check_response(response, debug)
response.raise_for_status()
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return filepath