dilnaka 0.0.1__tar.gz

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.

Potentially problematic release.


This version of dilnaka might be problematic. Click here for more details.

@@ -0,0 +1,10 @@
1
+ .env
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ *.pyo
6
+ *.pyd
7
+ .pytest_cache/
8
+ dist/
9
+ build/
10
+ *.egg-info/
dilnaka-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: dilnaka
3
+ Version: 0.0.1
4
+ Summary: Python SDK for Dilnaka file uploads
5
+ Project-URL: Homepage, https://dilnaka.tsnc.tech
6
+ Author: Dilnaka
7
+ License: MIT
8
+ Keywords: dilnaka,presigned-url,s3,sdk,uploads
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Requires-Python: >=3.9
14
+ Requires-Dist: python-dotenv>=1.0.0
15
+ Requires-Dist: requests>=2.31.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Dilnaka Python SDK
19
+
20
+ Python SDK for uploading files through the Dilnaka Upload API.
21
+
22
+ The SDK reads the API key from `.env` by default, then uses your Dilnaka backend to request a presigned S3 upload URL, uploads the file directly to S3, and calls the completion endpoint.
23
+
24
+ ## Install locally
25
+
26
+ ```bash
27
+ pip install -e .
28
+ ```
29
+
30
+ ## Configure `.env`
31
+
32
+ Copy the example file:
33
+
34
+ ```bash
35
+ cp .env.example .env
36
+ ```
37
+
38
+ On Windows PowerShell:
39
+
40
+ ```powershell
41
+ Copy-Item .env.example .env
42
+ ```
43
+
44
+ Then edit `.env`:
45
+
46
+ ```env
47
+ DILNAKA_API_KEY=dlk_dev_your_api_key_here
48
+ DILNAKA_BASE_URL=http://localhost:8000
49
+ DILNAKA_TIMEOUT=60
50
+ ```
51
+
52
+ ## Basic upload
53
+
54
+ ```python
55
+ from dilnaka import Dilnaka
56
+
57
+ client = Dilnaka()
58
+
59
+ uploaded = client.upload("./test-upload.txt")
60
+
61
+ print(uploaded.id)
62
+ print(uploaded.key)
63
+ print(uploaded.status)
64
+ ```
65
+
66
+ ## Explicit API key
67
+
68
+ ```python
69
+ from dilnaka import Dilnaka
70
+
71
+ client = Dilnaka(
72
+ api_key="dlk_dev_your_api_key_here",
73
+ base_url="http://localhost:8000",
74
+ )
75
+
76
+ uploaded = client.upload("./avatar.png", folder="avatars")
77
+ print(uploaded)
78
+ ```
79
+
80
+ ## Expected backend endpoints
81
+
82
+ The SDK expects your Caspian backend to expose:
83
+
84
+ ```txt
85
+ POST /v1/uploads/presign
86
+ POST /v1/uploads/complete
87
+ GET /v1/files
88
+ GET /v1/files/{file_id}
89
+ DELETE /v1/files/{file_id}
90
+ ```
91
+
92
+ ### Presign response shape
93
+
94
+ ```json
95
+ {
96
+ "fileId": "clx_file_id",
97
+ "fileKey": "uploads/2026/05/clx_file_id-test.txt",
98
+ "uploadUrl": "https://s3-presigned-url",
99
+ "expiresIn": 300,
100
+ "method": "PUT",
101
+ "headers": {
102
+ "Content-Type": "text/plain"
103
+ }
104
+ }
105
+ ```
106
+
107
+ ### Complete response shape
108
+
109
+ ```json
110
+ {
111
+ "fileId": "clx_file_id",
112
+ "status": "uploaded",
113
+ "key": "uploads/2026/05/clx_file_id-test.txt",
114
+ "originalName": "test.txt",
115
+ "contentType": "text/plain",
116
+ "size": 94,
117
+ "publicUrl": null
118
+ }
119
+ ```
120
+
121
+ ## Security model
122
+
123
+ The SDK never receives AWS credentials. It only receives a temporary presigned upload URL from your Dilnaka backend.
124
+
125
+ Your backend remains responsible for API key validation, scope checking, file validation, S3 key generation, metadata persistence, and upload completion verification.
@@ -0,0 +1,108 @@
1
+ # Dilnaka Python SDK
2
+
3
+ Python SDK for uploading files through the Dilnaka Upload API.
4
+
5
+ The SDK reads the API key from `.env` by default, then uses your Dilnaka backend to request a presigned S3 upload URL, uploads the file directly to S3, and calls the completion endpoint.
6
+
7
+ ## Install locally
8
+
9
+ ```bash
10
+ pip install -e .
11
+ ```
12
+
13
+ ## Configure `.env`
14
+
15
+ Copy the example file:
16
+
17
+ ```bash
18
+ cp .env.example .env
19
+ ```
20
+
21
+ On Windows PowerShell:
22
+
23
+ ```powershell
24
+ Copy-Item .env.example .env
25
+ ```
26
+
27
+ Then edit `.env`:
28
+
29
+ ```env
30
+ DILNAKA_API_KEY=dlk_dev_your_api_key_here
31
+ DILNAKA_BASE_URL=http://localhost:8000
32
+ DILNAKA_TIMEOUT=60
33
+ ```
34
+
35
+ ## Basic upload
36
+
37
+ ```python
38
+ from dilnaka import Dilnaka
39
+
40
+ client = Dilnaka()
41
+
42
+ uploaded = client.upload("./test-upload.txt")
43
+
44
+ print(uploaded.id)
45
+ print(uploaded.key)
46
+ print(uploaded.status)
47
+ ```
48
+
49
+ ## Explicit API key
50
+
51
+ ```python
52
+ from dilnaka import Dilnaka
53
+
54
+ client = Dilnaka(
55
+ api_key="dlk_dev_your_api_key_here",
56
+ base_url="http://localhost:8000",
57
+ )
58
+
59
+ uploaded = client.upload("./avatar.png", folder="avatars")
60
+ print(uploaded)
61
+ ```
62
+
63
+ ## Expected backend endpoints
64
+
65
+ The SDK expects your Caspian backend to expose:
66
+
67
+ ```txt
68
+ POST /v1/uploads/presign
69
+ POST /v1/uploads/complete
70
+ GET /v1/files
71
+ GET /v1/files/{file_id}
72
+ DELETE /v1/files/{file_id}
73
+ ```
74
+
75
+ ### Presign response shape
76
+
77
+ ```json
78
+ {
79
+ "fileId": "clx_file_id",
80
+ "fileKey": "uploads/2026/05/clx_file_id-test.txt",
81
+ "uploadUrl": "https://s3-presigned-url",
82
+ "expiresIn": 300,
83
+ "method": "PUT",
84
+ "headers": {
85
+ "Content-Type": "text/plain"
86
+ }
87
+ }
88
+ ```
89
+
90
+ ### Complete response shape
91
+
92
+ ```json
93
+ {
94
+ "fileId": "clx_file_id",
95
+ "status": "uploaded",
96
+ "key": "uploads/2026/05/clx_file_id-test.txt",
97
+ "originalName": "test.txt",
98
+ "contentType": "text/plain",
99
+ "size": 94,
100
+ "publicUrl": null
101
+ }
102
+ ```
103
+
104
+ ## Security model
105
+
106
+ The SDK never receives AWS credentials. It only receives a temporary presigned upload URL from your Dilnaka backend.
107
+
108
+ Your backend remains responsible for API key validation, scope checking, file validation, S3 key generation, metadata persistence, and upload completion verification.
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "dilnaka"
3
+ version = "0.0.1"
4
+ description = "Python SDK for Dilnaka file uploads"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = { text = "MIT" }
8
+ authors = [
9
+ { name = "Dilnaka" }
10
+ ]
11
+ dependencies = [
12
+ "requests>=2.31.0",
13
+ "python-dotenv>=1.0.0"
14
+ ]
15
+ keywords = ["dilnaka", "uploads", "s3", "presigned-url", "sdk"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent"
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://dilnaka.tsnc.tech"
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.hatch.build.targets.sdist]
31
+ exclude = [
32
+ "/examples",
33
+ "/.env",
34
+ "/test-upload.txt",
35
+ "/API_KEY_STRATEGY.md"
36
+ ]
@@ -0,0 +1,12 @@
1
+ from .client import Dilnaka
2
+ from .types import UploadedFile, PresignedUpload
3
+ from .errors import DilnakaError, DilnakaAPIError, DilnakaConfigError
4
+
5
+ __all__ = [
6
+ "Dilnaka",
7
+ "UploadedFile",
8
+ "PresignedUpload",
9
+ "DilnakaError",
10
+ "DilnakaAPIError",
11
+ "DilnakaConfigError",
12
+ ]
@@ -0,0 +1,219 @@
1
+ import mimetypes
2
+ from pathlib import Path
3
+ from typing import Any, Dict, Optional
4
+
5
+ import requests
6
+
7
+ from .config import load_config
8
+ from .errors import DilnakaAPIError
9
+ from .types import PresignedUpload, UploadedFile
10
+
11
+
12
+ class Dilnaka:
13
+ """Python SDK client for Dilnaka uploads.
14
+
15
+ Configuration order:
16
+ 1. Constructor args
17
+ 2. .env / environment variables
18
+
19
+ Required environment variable:
20
+ DILNAKA_API_KEY
21
+
22
+ Optional environment variables:
23
+ DILNAKA_BASE_URL
24
+ DILNAKA_TIMEOUT
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ api_key: Optional[str] = None,
30
+ base_url: Optional[str] = None,
31
+ timeout: Optional[int] = None,
32
+ env_file: str | None = None,
33
+ session: Optional[requests.Session] = None,
34
+ ):
35
+ self.config = load_config(
36
+ api_key=api_key,
37
+ base_url=base_url,
38
+ timeout=timeout,
39
+ env_file=env_file,
40
+ )
41
+ self.session = session or requests.Session()
42
+
43
+ def upload(
44
+ self,
45
+ file_path: str,
46
+ folder: str = "uploads",
47
+ content_type: Optional[str] = None,
48
+ metadata: Optional[Dict[str, Any]] = None,
49
+ ) -> UploadedFile:
50
+ """Upload a local file through the Dilnaka presigned URL flow."""
51
+
52
+ path = Path(file_path)
53
+ if not path.exists():
54
+ raise FileNotFoundError(f"File not found: {file_path}")
55
+ if not path.is_file():
56
+ raise ValueError(f"Path is not a file: {file_path}")
57
+
58
+ filename = path.name
59
+ size = path.stat().st_size
60
+ resolved_content_type = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
61
+
62
+ presigned = self.create_presigned_upload(
63
+ filename=filename,
64
+ content_type=resolved_content_type,
65
+ size=size,
66
+ folder=folder,
67
+ metadata=metadata,
68
+ )
69
+
70
+ upload_headers = dict(presigned.headers or {})
71
+ upload_headers.setdefault("Content-Type", resolved_content_type)
72
+
73
+ with open(path, "rb") as file:
74
+ upload_response = self.session.request(
75
+ method=presigned.method.upper(),
76
+ url=presigned.upload_url,
77
+ data=file,
78
+ headers=upload_headers,
79
+ timeout=self.config.timeout,
80
+ )
81
+
82
+ if upload_response.status_code not in (200, 201, 204):
83
+ raise DilnakaAPIError(
84
+ f"S3 upload failed with status {upload_response.status_code}.",
85
+ status_code=upload_response.status_code,
86
+ response_body=upload_response.text,
87
+ )
88
+
89
+ return self.complete_upload(presigned.file_id)
90
+
91
+ def create_presigned_upload(
92
+ self,
93
+ filename: str,
94
+ content_type: str,
95
+ size: int,
96
+ folder: str = "uploads",
97
+ metadata: Optional[Dict[str, Any]] = None,
98
+ ) -> PresignedUpload:
99
+ payload: Dict[str, Any] = {
100
+ "filename": filename,
101
+ "contentType": content_type,
102
+ "size": size,
103
+ "folder": folder,
104
+ }
105
+ if metadata:
106
+ payload["metadata"] = metadata
107
+
108
+ data = self._post("/v1/uploads/presign", payload)
109
+
110
+ return PresignedUpload(
111
+ file_id=data["fileId"],
112
+ file_key=data.get("fileKey") or data.get("key", ""),
113
+ upload_url=data["uploadUrl"],
114
+ expires_in=int(data.get("expiresIn", 300)),
115
+ method=data.get("method", "PUT"),
116
+ headers=data.get("headers") or {"Content-Type": content_type},
117
+ )
118
+
119
+ def complete_upload(self, file_id: str) -> UploadedFile:
120
+ data = self._post("/v1/uploads/complete", {"fileId": file_id})
121
+ return self._uploaded_file_from_response(data)
122
+
123
+ def list_files(self) -> list[UploadedFile]:
124
+ data = self._get("/v1/files")
125
+ if isinstance(data, list):
126
+ items = data
127
+ else:
128
+ items = data.get("files", [])
129
+ return [self._uploaded_file_from_response(item) for item in items]
130
+
131
+ def get_file(self, file_id: str) -> UploadedFile:
132
+ data = self._get(f"/v1/files/{file_id}")
133
+ return self._uploaded_file_from_response(data)
134
+
135
+ def delete_file(self, file_id: str) -> dict:
136
+ return self._delete(f"/v1/files/{file_id}")
137
+
138
+ def _uploaded_file_from_response(self, data: Dict[str, Any]) -> UploadedFile:
139
+ file_id = self._require_string_field(data, "file id", "fileId", "id")
140
+ file_key = self._require_string_field(data, "file key", "key")
141
+ status = self._require_string_field(data, "file status", "status")
142
+
143
+ return UploadedFile(
144
+ id=file_id,
145
+ key=file_key,
146
+ status=status,
147
+ original_name=data.get("originalName") or data.get("original_name") or "",
148
+ content_type=data.get("contentType") or data.get("content_type") or "application/octet-stream",
149
+ size=int(data.get("size", 0)),
150
+ public_url=data.get("publicUrl") or data.get("public_url"),
151
+ etag=data.get("etag"),
152
+ metadata=data.get("metadata"),
153
+ )
154
+
155
+ def _require_string_field(self, data: Dict[str, Any], field_name: str, *keys: str) -> str:
156
+ for key in keys:
157
+ value = data.get(key)
158
+ if isinstance(value, str) and value:
159
+ return value
160
+
161
+ raise DilnakaAPIError(f"Dilnaka API response missing {field_name}.")
162
+
163
+ def _headers(self) -> Dict[str, str]:
164
+ return {
165
+ "Authorization": f"Bearer {self.config.api_key}",
166
+ "Content-Type": "application/json",
167
+ "User-Agent": "dilnaka-python/0.1.0",
168
+ }
169
+
170
+ def _get(self, path: str) -> Any:
171
+ response = self.session.get(
172
+ f"{self.config.base_url}{path}",
173
+ headers=self._headers(),
174
+ timeout=self.config.timeout,
175
+ )
176
+ return self._parse_response(response)
177
+
178
+ def _post(self, path: str, payload: Dict[str, Any]) -> Any:
179
+ response = self.session.post(
180
+ f"{self.config.base_url}{path}",
181
+ json=payload,
182
+ headers=self._headers(),
183
+ timeout=self.config.timeout,
184
+ )
185
+ return self._parse_response(response)
186
+
187
+ def _delete(self, path: str) -> Any:
188
+ response = self.session.delete(
189
+ f"{self.config.base_url}{path}",
190
+ headers=self._headers(),
191
+ timeout=self.config.timeout,
192
+ )
193
+ return self._parse_response(response)
194
+
195
+ def _parse_response(self, response: requests.Response) -> Any:
196
+ if response.status_code >= 400:
197
+ message = response.text
198
+ try:
199
+ body = response.json()
200
+ message = body.get("error") or body.get("message") or message
201
+ except ValueError:
202
+ pass
203
+ raise DilnakaAPIError(
204
+ message,
205
+ status_code=response.status_code,
206
+ response_body=response.text,
207
+ )
208
+
209
+ if not response.text:
210
+ return {}
211
+
212
+ try:
213
+ return response.json()
214
+ except ValueError as exc:
215
+ raise DilnakaAPIError(
216
+ "Dilnaka API returned non-JSON response.",
217
+ status_code=response.status_code,
218
+ response_body=response.text,
219
+ ) from exc
@@ -0,0 +1,65 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ from dotenv import load_dotenv
7
+
8
+ from .errors import DilnakaConfigError
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class DilnakaConfig:
13
+ api_key: str
14
+ base_url: str
15
+ timeout: int
16
+
17
+
18
+ def load_config(
19
+ api_key: Optional[str] = None,
20
+ base_url: Optional[str] = None,
21
+ timeout: Optional[int] = None,
22
+ env_file: str | os.PathLike[str] | None = None,
23
+ ) -> DilnakaConfig:
24
+ """Load SDK config from explicit args first, then environment variables.
25
+
26
+ By default, python-dotenv searches for `.env` from the current working
27
+ directory upward. This matches normal app usage: the project using the SDK
28
+ owns the `.env` file.
29
+ """
30
+
31
+ if env_file is not None:
32
+ load_dotenv(dotenv_path=Path(env_file), override=False)
33
+ else:
34
+ load_dotenv(override=False)
35
+
36
+ resolved_api_key = api_key or os.getenv("DILNAKA_API_KEY")
37
+ resolved_base_url = base_url or os.getenv("DILNAKA_BASE_URL") or "http://localhost:8000"
38
+
39
+ if timeout is None:
40
+ raw_timeout = os.getenv("DILNAKA_TIMEOUT", "60")
41
+ try:
42
+ resolved_timeout = int(raw_timeout)
43
+ except ValueError as exc:
44
+ raise DilnakaConfigError("DILNAKA_TIMEOUT must be an integer.") from exc
45
+ else:
46
+ resolved_timeout = timeout
47
+
48
+ if not resolved_api_key:
49
+ raise DilnakaConfigError(
50
+ "Missing Dilnaka API key. Set DILNAKA_API_KEY in .env or pass api_key=... to Dilnaka()."
51
+ )
52
+
53
+ if not resolved_api_key.startswith(("dlk_dev_", "dlk_live_")):
54
+ raise DilnakaConfigError(
55
+ "Invalid Dilnaka API key format. Expected key starting with dlk_dev_ or dlk_live_."
56
+ )
57
+
58
+ if resolved_timeout <= 0:
59
+ raise DilnakaConfigError("timeout must be greater than 0.")
60
+
61
+ return DilnakaConfig(
62
+ api_key=resolved_api_key,
63
+ base_url=resolved_base_url.rstrip("/"),
64
+ timeout=resolved_timeout,
65
+ )
@@ -0,0 +1,15 @@
1
+ class DilnakaError(Exception):
2
+ """Base exception for Dilnaka SDK errors."""
3
+
4
+
5
+ class DilnakaConfigError(DilnakaError):
6
+ """Raised when required SDK configuration is missing or invalid."""
7
+
8
+
9
+ class DilnakaAPIError(DilnakaError):
10
+ """Raised when the Dilnaka API or S3 upload returns an error."""
11
+
12
+ def __init__(self, message: str, status_code: int | None = None, response_body: str | None = None):
13
+ super().__init__(message)
14
+ self.status_code = status_code
15
+ self.response_body = response_body
@@ -0,0 +1,25 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Dict, Optional
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class PresignedUpload:
7
+ file_id: str
8
+ file_key: str
9
+ upload_url: str
10
+ expires_in: int
11
+ method: str
12
+ headers: Dict[str, str]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class UploadedFile:
17
+ id: str
18
+ key: str
19
+ status: str
20
+ original_name: str
21
+ content_type: str
22
+ size: int
23
+ public_url: Optional[str] = None
24
+ etag: Optional[str] = None
25
+ metadata: Optional[Dict[str, Any]] = None