Skip to content

Add standard interface for handling file uploads in the Dioptra client #708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/dioptra/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@
#
# ACCESS THE FULL CC BY 4.0 LICENSE HERE:
# https://creativecommons.org/licenses/by/4.0/legalcode
from .base import DioptraFile
from .client import (
DioptraClient,
connect_json_dioptra_client,
connect_response_dioptra_client,
)
from .utils import select_files_in_directory, select_one_or_more_files

__all__ = [
"connect_response_dioptra_client",
"connect_json_dioptra_client",
"select_files_in_directory",
"select_one_or_more_files",
"DioptraClient",
"DioptraFile",
]
79 changes: 77 additions & 2 deletions src/dioptra/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@
#
# ACCESS THE FULL CC BY 4.0 LICENSE HERE:
# https://creativecommons.org/licenses/by/4.0/legalcode
import posixpath
import re
from abc import ABC, abstractmethod
from pathlib import Path
from dataclasses import dataclass
from io import BufferedReader
from pathlib import Path, PurePosixPath, PureWindowsPath
from posixpath import join as urljoin
from typing import Any, ClassVar, Generic, Protocol, TypeVar

T = TypeVar("T")

DOTS_REGEX = re.compile(r"^\.\.\.+$")


class DioptraClientError(Exception):
"""Base class for client errors"""
Expand Down Expand Up @@ -91,6 +97,52 @@ def json(self) -> dict[str, Any]:
... # fmt: skip


@dataclass
class DioptraFile(object):
"""A file to be uploaded to the Dioptra API.

Attributes:
filename: The name of the file.
stream: The file stream.
content_type: The content type of the file.
"""

filename: str
stream: BufferedReader
content_type: str | None

def __post_init__(self) -> None:
if PureWindowsPath(self.filename).as_posix() != str(PurePosixPath(self.filename)): # noqa: B950; fmt: skip
raise ValueError(
"Invalid filename (reason: filename is a Windows path): "
f"{self.filename}"
)

if posixpath.normpath(self.filename) != self.filename:
raise ValueError(
"Invalid filename (reason: filename is not normalized): "
f"{self.filename}"
)

if not PurePosixPath(self.filename).is_relative_to("."):
raise ValueError(
"Invalid filename (reason: filename is not relative to ./): "
f"{self.filename}"
)

if PurePosixPath("..") in PurePosixPath(posixpath.normpath(self.filename)).parents: # noqa: B950; fmt: skip
raise ValueError(
"Invalid filename (reason: filename is not a sub-directory of ./): "
f"{self.filename}"
)

if any([DOTS_REGEX.match(str(x)) for x in PurePosixPath(posixpath.normpath(self.filename)).parts]): # noqa: B950; fmt: skip
raise ValueError(
"Invalid filename (reason: filename contains a sub-directory name that "
f"is all dots): {self.filename}"
)


class DioptraSession(ABC, Generic[T]):
"""The interface for communicating with the Dioptra API."""

Expand All @@ -117,6 +169,8 @@ def make_request(
url: str,
params: dict[str, Any] | None = None,
json_: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: dict[str, DioptraFile | list[DioptraFile]] | None = None,
) -> DioptraResponseProtocol:
"""Make a request to the API.

Expand All @@ -129,6 +183,10 @@ def make_request(
params: The query parameters to include in the request. Optional, defaults
to None.
json_: The JSON data to include in the request. Optional, defaults to None.
data: A dictionary to send in the body of the request as part of a
multipart form. Optional, defaults to None.
files: Dictionary of "name": DioptraFile or lists of DioptraFile pairs to be
uploaded. Optional, defaults to None.

Returns:
The response from the API.
Expand Down Expand Up @@ -179,6 +237,8 @@ def post(
*parts,
params: dict[str, Any] | None = None,
json_: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: dict[str, DioptraFile | list[DioptraFile]] | None = None,
) -> T:
"""Make a POST request to the API.

Expand All @@ -188,6 +248,10 @@ def post(
params: The query parameters to include in the request. Optional, defaults
to None.
json_: The JSON data to include in the request. Optional, defaults to None.
data: A dictionary to send in the body of the request as part of a
multipart form. Optional, defaults to None.
files: Dictionary of "name": DioptraFile or lists of DioptraFile pairs to be
uploaded. Optional, defaults to None.

Returns:
The response from the API.
Expand Down Expand Up @@ -311,6 +375,8 @@ def _post(
*parts,
params: dict[str, Any] | None = None,
json_: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: dict[str, DioptraFile | list[DioptraFile]] | None = None,
) -> DioptraResponseProtocol:
"""Make a POST request to the API.

Expand All @@ -323,12 +389,21 @@ def _post(
params: The query parameters to include in the request. Optional, defaults
to None.
json_: The JSON data to include in the request. Optional, defaults to None.
data: A dictionary to send in the body of the request as part of a
multipart form. Optional, defaults to None.
files: Dictionary of "name": DioptraFile or lists of DioptraFile pairs to be
uploaded. Optional, defaults to None.

Returns:
A response object that implements the DioptraResponseProtocol interface.
"""
return self.make_request(
"post", self.build_url(endpoint, *parts), params=params, json_=json_
"post",
self.build_url(endpoint, *parts),
params=params,
json_=json_,
data=data,
files=files,
)

def _delete(
Expand Down
Loading
Loading