Skip to content

Commit ed1e193

Browse files
authored
Merge pull request #9 from OnedocLabs/ffo-82-update-python-sdk-to-new-api
Moves Python SDK to new API endpoint
2 parents 5b63401 + 7d01b17 commit ed1e193

File tree

3 files changed

+53
-84
lines changed

3 files changed

+53
-84
lines changed

packages/client-py/onedoc/html_builder.py

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self, title=None):
1313
</html>"""
1414
self._watermark = '<div id="watermark-onedoc" > <a href="https://www.onedoclabs.com/" target="_blank"> <svg style="transform: rotate(90deg);display:inline;margin-top:30px;" width=75 xmlns="http://www.w3.org/2000/svg" x="0" y="0" enableBackground="new 0 0 46.15 9.31" version="1.1" viewBox="0 0 46.15 9.31" xmlSpace="preserve" fill="black" {...props} > <path d="M10 9.13V2.55h1.83v.91c.35-.62 1.13-1.09 2.07-1.09.71 0 1.32.24 1.81.71s.74 1.15.74 2.03v4.02h-1.88V5.6c0-.96-.5-1.5-1.28-1.5-.85 0-1.42.62-1.42 1.55v3.48H10zM23.84 6.48h-4.83c.23.83.83 1.24 1.79 1.24.74 0 1.43-.22 2.05-.64l.74 1.28c-.8.61-1.76.91-2.88.91-1.16 0-2.05-.34-2.67-1-.61-.66-.92-1.47-.92-2.45 0-1 .32-1.81.96-2.46.64-.66 1.48-.98 2.51-.98.97 0 1.76.3 2.39.89.62.59.94 1.39.94 2.41-.01.23-.04.5-.08.8zM19 5.13h3.09c-.18-.76-.73-1.22-1.51-1.22-.76 0-1.38.46-1.58 1.22zM29.43 0h1.88v9.13h-1.82v-.71c-.52.59-1.16.88-1.96.88-.92 0-1.69-.32-2.31-.98-.61-.66-.92-1.47-.92-2.47 0-.98.31-1.8.92-2.46.62-.66 1.39-1 2.31-1 .74 0 1.38.26 1.89.8V0zm-.39 4.6c-.31-.34-.71-.5-1.2-.5s-.89.17-1.21.5c-.31.34-.47.74-.47 1.22 0 .49.16.91.47 1.25.32.34.72.5 1.21.5s.89-.17 1.2-.5c.32-.34.48-.76.48-1.25 0-.47-.15-.88-.48-1.22zM33.03 8.31c-.66-.67-.98-1.5-.98-2.47s.32-1.8.98-2.46c.66-.67 1.51-1.01 2.55-1.01 1.04 0 1.91.34 2.57 1.01.66.66 1 1.49 1 2.46s-.34 1.8-1 2.47c-.66.66-1.52 1-2.57 1-1.04 0-1.89-.34-2.55-1zm3.74-3.68c-.32-.34-.72-.5-1.19-.5s-.86.17-1.19.5c-.32.32-.48.73-.48 1.2 0 .49.16.9.48 1.24.32.32.72.49 1.19.49s.86-.17 1.19-.49c.32-.34.49-.74.49-1.24 0-.47-.17-.88-.49-1.2zM40.5 8.31c-.65-.65-.97-1.47-.97-2.48s.32-1.83.98-2.47c.66-.65 1.5-.97 2.54-.97 1.36 0 2.55.67 3.09 1.87l-1.5.8c-.38-.62-.9-.94-1.56-.94-.49 0-.89.17-1.21.49-.32.32-.48.73-.48 1.21 0 .49.16.91.47 1.24.32.32.72.48 1.2.48.66 0 1.27-.38 1.55-.92l1.52.9c-.58 1.07-1.74 1.75-3.12 1.75-1.02 0-1.86-.32-2.51-.96zM9.26 4.7c0-1.29-.44-2.36-1.34-3.25C7.03.55 5.94.1 4.63.1c-1.3 0-2.39.45-3.29 1.35C.45 2.34 0 3.43 0 4.71c0 .37.05.72.12 1.05l4.3-3.39h2.22v6.46c.47-.22.9-.5 1.29-.88.89-.89 1.33-1.97 1.33-3.25z"></path> <path d="M1.49 8.09c.62.56 1.34.94 2.17 1.1v-2.8l-2.17 1.7z"></path> </svg> <a /> </div>'
1515

16-
def build(self, document, style_sheets=None, dev=True):
16+
def build(self, document, style_sheets=None):
1717
if style_sheets:
1818
for path in style_sheets:
1919
self._start += f'<link rel="stylesheet" href="{path}" />'
@@ -23,20 +23,6 @@ def build(self, document, style_sheets=None, dev=True):
2323

2424
self._middle += document
2525

26-
if dev:
27-
# adds watermark for dev renderings
28-
self._start += """
29-
<style>
30-
@page {
31-
@left-middle {
32-
content: flow(watermark);
33-
}
34-
}
35-
#watermark-onedoc { -prince-flow: static(watermark, start) }
36-
</style>"""
37-
38-
self._middle += self._watermark
39-
4026
content = self._start + self._middle + self._end
4127

4228
return content

packages/client-py/onedoc/onedoc.py

Lines changed: 42 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import requests
22
import json
3+
import time
4+
import datetime
5+
from datetime import timezone
6+
import mimetypes
37

48
from pikepdf import Pdf
59

@@ -16,102 +20,73 @@
1620
}
1721

1822
class Onedoc:
19-
def __init__(self, api_key: str, endpoint: str = "https://app.onedoclabs.com"):
23+
def __init__(self, api_key: str, endpoint: str = "https://api.fileforge.com"):
2024
self.api_key = api_key
2125
self.endpoint = endpoint
2226

2327
def _build_url(self, path: str) -> str:
2428
return f"{self.endpoint}{path}"
2529

26-
def _upload_to_signed_url(self, url_to_fs: str, path: str, file_body: Any, file_options: Dict = None) -> Dict:
27-
url = f"{url_to_fs}"
28-
29-
options = {**DEFAULT_FILE_OPTIONS, **(file_options or {})}
30-
headers = {"x-upsert": str(options["upsert"])}
31-
files = None
32-
33-
if isinstance(file_body, bytes):
34-
files = {"file": (path, file_body, options["contentType"])}
35-
headers["cache-control"] = f"max-age={options['cacheControl']}"
36-
else:
37-
headers["Content-Type"] = options["contentType"]
38-
file_body = file_body.encode('utf-8')
39-
40-
response = requests.put(url, data=file_body, headers=headers, files=files)
41-
data = response.json()
42-
43-
if response.ok:
44-
return {"data": {"path": path, "fullPath": data.get("Key")}, "error": None}
45-
else:
46-
return {"data": None, "error": data}
47-
4830
def render(self, document: Dict) -> Dict:
4931
assets = document.get('assets', []) + [{"path": "/index.html", "content": document['html']}]
5032
test = document.get('test', True)
5133
save = document.get('save', False)
5234

5335
expires_in = document.get('expiresIn', 1)
54-
55-
# Initiate document rendering process
56-
information_response = requests.post(
57-
self._build_url("/api/docs/initiate"),
58-
headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
59-
json={"assets": assets}
36+
# Add expires_in (in days) to the current time to get the expiration time
37+
expires_at = int(time.time()) + (expires_in * 24 * 60 * 60)
38+
# Convert to timestamp with timezone
39+
expires_at = datetime.datetime.fromtimestamp(expires_at, timezone.utc).isoformat()
40+
41+
files = (
42+
('options', (None, json.dumps({
43+
'test': test,
44+
'host': save,
45+
'expiresAt': expires_at,
46+
'fileName': document.get('title', "document")
47+
}), 'application/json')),
6048
)
6149

50+
for asset in assets:
51+
if asset and asset.get('path') == "/index.html":
6252

63-
if information_response.status_code != 200:
64-
return {
65-
"file": None,
66-
"error": information_response.json().get('error', "An unknown error has occurred"),
67-
"info": {"status": information_response.status_code},
68-
}
69-
70-
response = information_response.json()
71-
signed_urls = response['signedUrls']
72-
73-
for e in signed_urls:
74-
asset = next((item for item in document.get('assets', []) if item['path'] == e['path']), None)
75-
76-
if asset and asset.get('content'):
77-
self._upload_to_signed_url(e['signedUrl'], e['path'], asset['content'])
78-
79-
elif e['path'] == "/index.html":
8053
html_builder = _HtmlBuilder(document.get('title'))
8154
style_sheets = [asset['path'] for asset in document.get('assets', []) if asset['path'].endswith(".css")]
82-
html = html_builder.build(document['html'], style_sheets, test)
83-
self._upload_to_signed_url(e['signedUrl'], e['path'], html)
84-
85-
doc_response = requests.post(
86-
self._build_url("/api/docs/generate"),
87-
headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
88-
json=json.dumps({
89-
"uploadURL":response["uploadURL"],
90-
"username":response["username"],
91-
"bucket":response["bucket"],
92-
"signedUrls":response["signedUrls"],
93-
"password":response["password"],
94-
"title": document.get('title', "document"),
95-
"test": test,
96-
"save": save,
97-
"expiresIn": expires_in
98-
})
55+
html = html_builder.build(document['html'], style_sheets)
56+
57+
files += (
58+
('files', ('index.html', html, 'text/html')),
59+
)
60+
elif asset and asset.get('content'):
61+
files += (
62+
('files', (asset['path'], asset['content'], mimetypes.guess_type(asset['path'])[0] or 'application/octet-stream')),
63+
)
64+
65+
generation = requests.post(
66+
self._build_url("/pdf/generate"),
67+
headers={"x-api-key": self.api_key},
68+
files=files
9969
)
10070

101-
if doc_response.status_code != 200:
102-
return doc_response.__dict__
71+
if generation.status_code != 201:
72+
return {
73+
"file": None,
74+
"link": None,
75+
"error": generation.json(),
76+
"info": {},
77+
}
10378

10479
if not save:
10580
return {
106-
"file": doc_response.content,
81+
"file": generation.content,
10782
"link": None,
10883
"error": None,
10984
"info": {},
11085
}
11186
else:
11287
return {
11388
"file": None,
114-
"link": doc_response.json().get('url_link'),
89+
"link": generation.json().get('url'),
11590
"error": None,
11691
"info": {},
11792
}

packages/client-py/test.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,23 @@
2121
"assets":[
2222
{
2323
"content": css_content ,
24-
"path": "/styles.css"
24+
"path": "styles.css"
2525
}
2626
]
2727
}
2828

29+
# Start a timer
30+
import time
31+
start = time.time()
32+
2933
# Render the document
3034
result = onedoc.render(document)
3135

32-
print(result)
36+
# End the timer
37+
end = time.time()
38+
print("Time elapsed: ", end - start)
39+
40+
# print(result)
3341
#for files that are not saved, remember to use "wb" when writing file
3442
# onedoc = Onedoc(api_key)
3543

0 commit comments

Comments
 (0)