Skip to content

Commit 4961366

Browse files
committed
Improve documentation, add type hints, start to break py2
1 parent 764823d commit 4961366

21 files changed

Lines changed: 281 additions & 209 deletions

Makefile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,8 @@ run-benchmark:
3131
format:
3232
black frameioclient
3333

34+
view-docs:
35+
cd docs && pip install -r requirements.txt && make dev
36+
3437
publish-docs:
35-
cd docs && pip install -r requirements.txt && make jekyll && make publish
38+
cd docs && pip install -r requirements.txt && make jekyll && make publish

docs/Makefile

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,8 @@ rst:
2929
sphinx-build -b rst . dist/rst
3030

3131
html:
32-
sphinx-build -b html . dist/html
32+
sphinx-build -b html . dist/html
33+
34+
dev:
35+
sphinx-autobuild -b html . _build/html
36+

docs/classes/search.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
Search
22
===================
3+
4+
.. autoclass:: frameioclient.Search
5+
:members:

docs/conf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
# -- Project information -----------------------------------------------------
2020

2121
project = PACKAGE_TITLE
22-
copyright = 'MIT License 2021, Frame.io'
22+
copyright = 'MIT License 2022, Frame.io'
2323
author = AUTHOR_NAME
2424

2525
# The full version, including alpha/beta/rc tags
@@ -36,6 +36,7 @@
3636
'sphinx.ext.napoleon',
3737
'sphinxcontrib.restbuilder',
3838
'sphinx_jekyll_builder',
39+
'sphinx_autodoc_typehints'
3940
]
4041

4142
# Add any paths that contain templates here, relative to this directory.

docs/requirements.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,6 @@ xxhash
88
furo
99
analytics-python
1010
token-bucket
11-
speedtest-cli
11+
speedtest-cli
12+
sphinx-autobuild
13+
sphinx-autodoc-typehints

examples/projects/download_project.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from frameioclient.lib.utils import Utils
1+
from frameioclient.lib.utils import FormatTypes, Utils
22
import os
33
from pathlib import Path
44

@@ -34,7 +34,7 @@ def demo_project_download(project_id):
3434
# pdb.set_trace()
3535

3636
print(f"Found {item_count} items")
37-
print(f"Took {elapsed} second to download {Utils.format_bytes(folder_size, type='size')} for project: {client.projects.get(project_id)['name']}")
37+
print(f"Took {elapsed} second to download {Utils.format_value(folder_size, type=FormatTypes.SIZE)} for project: {client.projects.get(project_id)['name']}")
3838
print("\n")
3939

4040
if __name__ == "__main__":

frameioclient/lib/transfer.py

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,21 @@
33
import os
44
import time
55
from pprint import pprint
6-
from typing import Dict, List
76
from random import randint
7+
from typing import Dict, List
88

99
import requests
1010

11-
from .exceptions import (
12-
AssetChecksumMismatch,
13-
AssetChecksumNotPresent,
14-
DownloadException,
15-
)
11+
from .exceptions import (AssetChecksumMismatch, AssetChecksumNotPresent,
12+
DownloadException)
1613
from .logger import SDKLogger
17-
from .utils import Utils
14+
from .utils import FormatTypes, Utils
1815

1916
logger = SDKLogger("downloads")
2017

2118
from .bandwidth import DiskBandwidth, NetworkBandwidth
22-
from .exceptions import (
23-
AssetNotFullyUploaded,
24-
DownloadException,
25-
WatermarkIDDownloadException,
26-
)
19+
from .exceptions import (AssetNotFullyUploaded, DownloadException,
20+
WatermarkIDDownloadException)
2721
from .transport import HTTPClient
2822

2923

@@ -282,7 +276,7 @@ def _download_whole(self, url: str):
282276
print(
283277
"Beginning download -- {} -- {}".format(
284278
self.asset["name"],
285-
Utils.format_bytes(self.downloader.filesize, type="size"),
279+
Utils.format_value(self.downloader.filesize, type=FormatTypes.SIZE),
286280
)
287281
)
288282

@@ -301,12 +295,12 @@ def _download_whole(self, url: str):
301295
raise e
302296

303297
download_time = time.time() - start_time
304-
download_speed = Utils.format_bytes(
298+
download_speed = Utils.format_value(
305299
math.ceil(self.downloader.filesize / (download_time))
306300
)
307301
print(
308302
"Downloaded {} at {}".format(
309-
Utils.format_bytes(self.downloader.filesize, type="size"),
303+
Utils.format_value(self.downloader.filesize, type=FormatTypes.SIZE),
310304
download_speed,
311305
)
312306
)
@@ -386,7 +380,7 @@ def multi_thread_download(self):
386380
print(
387381
"Multi-part download -- {} -- {}".format(
388382
self.downloader.asset["name"],
389-
Utils.format_bytes(self.downloader.filesize, type="size"),
383+
Utils.format_value(self.downloader.filesize, type=FormatTypes.SIZE),
390384
)
391385
)
392386

@@ -435,7 +429,7 @@ def multi_thread_download(self):
435429
# Log completion event
436430
SDKLogger("downloads").info(
437431
"Downloaded {} at {}".format(
438-
Utils.format_bytes(self.downloader.filesize, type="size"),
432+
Utils.format_value(self.downloader.filesize, type=FormatTypes.SIZE),
439433
download_speed,
440434
)
441435
)

frameioclient/lib/transport.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import concurrent.futures
22
import threading
33
import time
4+
from typing import Dict, Optional
45

56
import requests
67
from requests.adapters import HTTPAdapter
@@ -13,17 +14,27 @@
1314
from .version import ClientVersion
1415

1516

17+
class HTTPMethods:
18+
GET = 'get'
19+
POST = 'post'
20+
PUT = 'put'
21+
DELETE = 'delete'
22+
PATCH = 'patch'
23+
HEAD = 'head'
24+
1625
class HTTPClient(object):
1726
"""HTTP Client base that automatically handles the following:
18-
- Shared thread/session object
19-
- Client version headers
20-
- Automated retries
27+
- Shared thread/session object
28+
- Client version headers
29+
- Automated retries
2130
22-
Args:
23-
threads (int): Number of threads to use concurrently.
2431
"""
2532

26-
def __init__(self, threads=default_thread_count):
33+
def __init__(self, threads: Optional[int] = default_thread_count):
34+
"""
35+
:param threads: Number of threads to use concurrently.
36+
"""
37+
2738
# Setup number of threads to use
2839
self.threads = threads
2940

@@ -72,7 +83,7 @@ class APIClient(HTTPClient, object):
7283
progress (bool): If True, show status bars in console.
7384
"""
7485

75-
def __init__(self, token, host, threads, progress):
86+
def __init__(self, token: str, host: str, threads: int, progress: bool):
7687
super().__init__(threads)
7788
self.host = host
7889
self.token = token
@@ -82,10 +93,10 @@ def __init__(self, token, host, threads, progress):
8293
self.session = self._get_session()
8394
self.auth_header = {"Authorization": "Bearer {}".format(self.token)}
8495

85-
def _format_api_call(self, endpoint):
96+
def _format_api_call(self, endpoint: str):
8697
return "{}/v2{}".format(self.host, endpoint)
8798

88-
def _api_call(self, method, endpoint, payload={}, limit=None):
99+
def _api_call(self, method, endpoint: str, payload: Dict = {}, limit: Optional[int] = None):
89100
headers = {**self.shared_headers, **self.auth_header}
90101

91102
r = self.session.request(
@@ -117,7 +128,7 @@ def _api_call(self, method, endpoint, payload={}, limit=None):
117128

118129
return r.raise_for_status()
119130

120-
def get_specific_page(self, method, endpoint, payload, page):
131+
def get_specific_page(self, method: HTTPMethods, endpoint: str, payload: Dict, page: int):
121132
"""
122133
Gets a specific page for that endpoint, used by Pagination Class
123134
@@ -127,11 +138,11 @@ def get_specific_page(self, method, endpoint, payload, page):
127138
payload (dict): Request payload
128139
page (int): What page to get
129140
"""
130-
if method == "get":
141+
if method == HTTPMethods.GET:
131142
endpoint = "{}?page={}".format(endpoint, page)
132143
return self._api_call(method, endpoint)
133144

134-
if method == "post":
145+
if method == HTTPMethods.POST:
135146
payload["page"] = page
136147
return self._api_call(method, endpoint, payload=payload)
137148

frameioclient/lib/upload.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
import os
1+
import concurrent.futures
22
import math
3-
import requests
3+
import os
44
import threading
5-
import concurrent.futures
5+
from typing import List
6+
7+
import requests
68

7-
from .utils import Utils
9+
from .utils import FormatTypes, Utils
810

911
thread_local = threading.local()
1012

@@ -18,15 +20,14 @@ def __init__(self, asset=None, file=None):
1820
self.file_num = 0
1921
self.futures = []
2022

21-
def _calculate_chunks(self, total_size, chunk_count):
22-
"""Calculate chunk size
23+
def _calculate_chunks(self, total_size: int, chunk_count: int) -> List[int]:
24+
"""
25+
Calculate chunk size
2326
24-
Args:
25-
total_size (int): Total filesize in bytes
26-
chunk_count (int): Total number of URL's we got back from the API
27+
:param total_size: Total filesize in bytes
28+
:param chunk_count: Total number of URL's we got back from the API
2729
28-
Returns:
29-
chunk_offsets (list): List of chunk offsets
30+
:return chunk_offsets: List of chunk offsets
3031
"""
3132
self.chunk_size = int(math.ceil(total_size / chunk_count))
3233

@@ -43,7 +44,7 @@ def _get_session(self):
4344
thread_local.session = requests.Session()
4445
return thread_local.session
4546

46-
def _smart_read_chunk(self, chunk_offset, is_final_chunk):
47+
def _smart_read_chunk(self, chunk_offset: int, is_final_chunk: bool) -> bytes:
4748
with open(os.path.realpath(self.file.name), "rb") as file:
4849
file.seek(chunk_offset, 0)
4950
if (
@@ -54,7 +55,7 @@ def _smart_read_chunk(self, chunk_offset, is_final_chunk):
5455
data = file.read(self.chunk_size)
5556
return data
5657

57-
def _upload_chunk(self, task):
58+
def _upload_chunk(self, task) -> int:
5859
url = task[0]
5960
chunk_offset = task[1]
6061
chunk_id = task[2]
@@ -141,7 +142,7 @@ def recursive_upload(self, client, folder, parent_asset_id):
141142

142143
complete_dir_obj = os.path.join(folder, file_p)
143144
print(
144-
"Starting {:02d}/{}, Size: {}, Name: {}".format(self.file_num, self.file_count, Utils.format_bytes(os.path.getsize(complete_dir_obj), type='size'), file_p)
145+
"Starting {:02d}/{}, Size: {}, Name: {}".format(self.file_num, self.file_count, Utils.format_value(os.path.getsize(complete_dir_obj), type=FormatTypes.SIZE), file_p)
145146
)
146147
client.assets.upload(parent_asset_id, complete_dir_obj)
147148

0 commit comments

Comments
 (0)