nlbone 0.1.29__py3-none-any.whl → 0.1.31__py3-none-any.whl

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.
@@ -0,0 +1,177 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, AsyncIterator, Optional
5
+
6
+ import httpx
7
+
8
+ from nlbone.core.ports.files import FileServicePort
9
+ from nlbone.config.settings import get_settings
10
+
11
+
12
+ class FileServiceException(RuntimeError):
13
+ def __init__(self, status: int, detail: Any | None = None):
14
+ super().__init__(f"Uploadchi HTTP {status}: {detail}")
15
+ self.status = status
16
+ self.detail = detail
17
+
18
+
19
+ def _auth_headers(token: str | None) -> dict[str, str]:
20
+ return {"Authorization": f"Bearer {token}"} if token else {}
21
+
22
+
23
+ def _build_list_query(
24
+ limit: int,
25
+ offset: int,
26
+ filters: dict[str, Any] | None,
27
+ sort: list[tuple[str, str]] | None,
28
+ ) -> dict[str, Any]:
29
+ q: dict[str, Any] = {"limit": limit, "offset": offset}
30
+ if filters:
31
+ # سرور شما `filters` را به صورت string می‌گیرد؛
32
+ # اگر سمت سرور JSON هم قبول می‌کند، این بهتر است:
33
+ q["filters"] = json.dumps(filters)
34
+ if sort:
35
+ # "created_at:desc,id:asc"
36
+ q["sort"] = ",".join([f"{f}:{o}" for f, o in sort])
37
+ return q
38
+
39
+
40
+ class UploadchiClient(FileServicePort):
41
+ """
42
+ httpx-based client for the Uploadchi microservice.
43
+
44
+ Base URL نمونه: http://uploadchi.internal/api/v1/files
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ base_url: Optional[str] = None,
50
+ timeout_seconds: Optional[float] = None,
51
+ client: httpx.AsyncClient | None = None,
52
+ ) -> None:
53
+ s = get_settings()
54
+ self._base_url = base_url or str(s.UPLOADCHI_BASE_URL)
55
+ self._timeout = timeout_seconds or float(s.HTTP_TIMEOUT_SECONDS)
56
+ # اگر کلاینت تزریق نشد، خودمان می‌سازیم
57
+ self._client = client or httpx.AsyncClient(
58
+ base_url=self._base_url,
59
+ timeout=self._timeout,
60
+ follow_redirects=True,
61
+ )
62
+
63
+ async def aclose(self) -> None:
64
+ await self._client.aclose()
65
+
66
+ # ---------- Endpoints ----------
67
+
68
+ async def upload_file(
69
+ self,
70
+ file_bytes: bytes,
71
+ filename: str,
72
+ params: dict[str, Any] | None = None,
73
+ token: str | None = None,
74
+ ) -> dict:
75
+ """
76
+ POST "" → returns FileOut (dict)
77
+ fields:
78
+ - file: Upload (multipart)
79
+ - other params (e.g., bucket, folder, content_type, ...)
80
+ """
81
+ files = {"file": (filename, file_bytes)}
82
+ data = (params or {}).copy()
83
+ r = await self._client.post(
84
+ url="",
85
+ files=files,
86
+ data=data,
87
+ headers=_auth_headers(token),
88
+ )
89
+ if r.status_code >= 400:
90
+ raise FileServiceException(r.status_code, r.text)
91
+ return r.json()
92
+
93
+ async def commit_file(
94
+ self,
95
+ file_id: int,
96
+ client_id: str,
97
+ token: str | None = None,
98
+ ) -> None:
99
+ """
100
+ POST "/{file_id}/commit" 204
101
+ """
102
+ r = await self._client.post(
103
+ f"/{file_id}/commit",
104
+ headers=_auth_headers(token),
105
+ params={"client_id": client_id} if client_id else None,
106
+ )
107
+ if r.status_code not in (204, 200):
108
+ raise FileServiceException(r.status_code, r.text)
109
+
110
+ async def list_files(
111
+ self,
112
+ limit: int = 10,
113
+ offset: int = 0,
114
+ filters: dict[str, Any] | None = None,
115
+ sort: list[tuple[str, str]] | None = None,
116
+ token: str | None = None,
117
+ ) -> dict:
118
+ """
119
+ GET "" → returns PaginateResponse-like dict
120
+ { "data": [...], "total_count": int | null, "total_page": int | null }
121
+ """
122
+ q = _build_list_query(limit, offset, filters, sort)
123
+ r = await self._client.get("", params=q, headers=_auth_headers(token))
124
+ if r.status_code >= 400:
125
+ raise FileServiceException(r.status_code, r.text)
126
+ return r.json()
127
+
128
+ async def get_file(
129
+ self,
130
+ file_id: int,
131
+ token: str | None = None,
132
+ ) -> dict:
133
+ """
134
+ GET "/{file_id}" → FileOut dict
135
+ """
136
+ r = await self._client.get(f"/{file_id}", headers=_auth_headers(token))
137
+ if r.status_code >= 400:
138
+ raise FileServiceException(r.status_code, r.text)
139
+ return r.json()
140
+
141
+ async def download_file(
142
+ self,
143
+ file_id: int,
144
+ token: str | None = None,
145
+ ) -> tuple[AsyncIterator[bytes], str, str]:
146
+ """
147
+ GET "/{file_id}/download" → stream + headers (filename, content-type)
148
+ """
149
+ r = await self._client.get(f"/{file_id}/download", headers=_auth_headers(token))
150
+ if r.status_code >= 400:
151
+ text = await r.aread()
152
+ raise FileServiceException(r.status_code, text.decode(errors="ignore"))
153
+
154
+ disp = r.headers.get("content-disposition", "")
155
+ filename = (
156
+ disp.split("filename=", 1)[1].strip("\"'") if "filename=" in disp else f"file-{file_id}"
157
+ )
158
+ media_type = r.headers.get("content-type", "application/octet-stream")
159
+
160
+ async def _aiter() -> AsyncIterator[bytes]:
161
+ async for chunk in r.aiter_bytes():
162
+ yield chunk
163
+ await r.aclose()
164
+
165
+ return _aiter(), filename, media_type
166
+
167
+ async def delete_file(
168
+ self,
169
+ file_id: int,
170
+ token: str | None = None,
171
+ ) -> None:
172
+ """
173
+ DELETE "/{file_id}" → 204
174
+ """
175
+ r = await self._client.delete(f"/{file_id}", headers=_auth_headers(token))
176
+ if r.status_code not in (204, 200):
177
+ raise FileServiceException(r.status_code, r.text)
nlbone/config/settings.py CHANGED
@@ -54,6 +54,8 @@ class Settings(BaseSettings):
54
54
  # ---------------------------
55
55
  REDIS_URL: str = Field(default="redis://localhost:6379/0")
56
56
 
57
+ UPLOADCHI_BASE_URL: AnyHttpUrl = Field(default="https://uploadchi.numberland.ir/v1/files")
58
+
57
59
  model_config = SettingsConfigDict(
58
60
  env_prefix="NLBONE_",
59
61
  env_file=None,
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+ from typing import Protocol, runtime_checkable, AsyncIterator, Any
3
+
4
+ @runtime_checkable
5
+ class FileServicePort(Protocol):
6
+ async def upload_file(
7
+ self,
8
+ file_bytes: bytes,
9
+ filename: str,
10
+ params: dict[str, Any] | None = None,
11
+ token: str | None = None,
12
+ ) -> dict: ...
13
+
14
+ async def commit_file(
15
+ self,
16
+ file_id: int,
17
+ client_id: str,
18
+ token: str | None = None,
19
+ ) -> None: ...
20
+
21
+ async def list_files(
22
+ self,
23
+ limit: int = 10,
24
+ offset: int = 0,
25
+ filters: dict[str, Any] | None = None,
26
+ sort: list[tuple[str, str]] | None = None,
27
+ token: str | None = None,
28
+ ) -> dict: ...
29
+
30
+ async def get_file(
31
+ self,
32
+ file_id: int,
33
+ token: str | None = None,
34
+ ) -> dict: ...
35
+
36
+ async def download_file(
37
+ self,
38
+ file_id: int,
39
+ token: str | None = None,
40
+ ) -> tuple[AsyncIterator[bytes], str, str]:
41
+ ...
42
+
43
+ async def delete_file(
44
+ self,
45
+ file_id: int,
46
+ token: str | None = None,
47
+ ) -> None: ...
nlbone/di/container.py CHANGED
@@ -1,7 +1,11 @@
1
+ from nlbone.adapters.http_clients.uploadchi import UploadchiClient
1
2
  from nlbone.config.settings import Settings
2
3
  from nlbone.adapters.auth.keycloak import KeycloakAuthService
4
+ from nlbone.core.ports.files import FileServicePort
5
+
3
6
 
4
7
  class Container:
5
8
  def __init__(self, settings: Settings | None = None):
6
9
  self.settings = settings or Settings()
7
- self.auth: KeycloakAuthService = KeycloakAuthService(self.settings)
10
+ self.auth: KeycloakAuthService = KeycloakAuthService(self.settings)
11
+ self.file_service: FileServicePort = UploadchiClient()
@@ -0,0 +1 @@
1
+ from .db import get_session, get_async_session
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nlbone
3
- Version: 0.1.29
3
+ Version: 0.1.31
4
4
  Summary: Backbone package for interfaces and infrastructure in Python projects
5
5
  Author-email: Amir Hosein Kahkbazzadeh <a.khakbazzadeh@gmail.com>
6
6
  License: MIT
@@ -19,15 +19,16 @@ nlbone/adapters/db/sqlalchemy/query/ordering.py,sha256=THbuxZmoFZzJIa28KfDQ6ioS8
19
19
  nlbone/adapters/db/sqlalchemy/query/types.py,sha256=M2j6SOSyFkLuyXq4kvPYgZQYz5TKCBe3osoIIN1yfBI,287
20
20
  nlbone/adapters/http_clients/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
21
  nlbone/adapters/http_clients/email_gateway.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ nlbone/adapters/http_clients/uploadchi.py,sha256=tr-huESnVDg08FQh3QTFST7_JQz7dPShr2CAX9CQYLU,5737
22
23
  nlbone/adapters/messaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
24
  nlbone/adapters/messaging/redis.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
25
  nlbone/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
26
  nlbone/config/logging.py,sha256=68WRQejEpL6eHEY_cOgdlOjndKc-RWth0n4YmXnceC8,5041
26
- nlbone/config/settings.py,sha256=jkaVzlKuQKASd6-xT69RAEbMcbol6PUKa86QPpjami0,2272
27
+ nlbone/config/settings.py,sha256=ElE--1waYQ2o_5u7HzHi800zsK9n_oJBz1VnewYm-Y0,2368
27
28
  nlbone/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
- nlbone/core/{__init__.py},sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
29
  nlbone/core/application/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
30
30
  nlbone/core/application/services.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
+ nlbone/core/application/services/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
32
  nlbone/core/application/use_cases/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
33
  nlbone/core/application/use_cases/register_user.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
33
34
  nlbone/core/domain/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -35,16 +36,18 @@ nlbone/core/domain/events.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,
35
36
  nlbone/core/domain/models.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
37
  nlbone/core/ports/__init__.py,sha256=J24ldeLIQ_AWqKpdNbtaEWq4-G4cyWx8XEG0Dt6keao,29
37
38
  nlbone/core/ports/auth.py,sha256=v2NiH8FzKXZ1MabzQxaK7AQvnt-GQindYIki90swTE4,492
39
+ nlbone/core/ports/files.py,sha256=dYBMFsaesyIVaWxzTShGFMFzRZWbWcQtPdzhELY6t4A,1119
38
40
  nlbone/core/ports/messaging.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
39
41
  nlbone/core/ports/repo.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
40
42
  nlbone/di/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
41
- nlbone/di/container.py,sha256=7-lcrH1q9NmNLY7VMpLfPJZYKsvNuXP2U6gOYcCwgPo,304
43
+ nlbone/di/container.py,sha256=nzWx8nctyBMAERoqjolt0vWS38H2JH2QhqVaLvAvF8U,488
42
44
  nlbone/interfaces/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
43
45
  nlbone/interfaces/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
44
- nlbone/interfaces/api/dependencies.py,sha256=IqDVq1lcCCxd22FBUg523lVANM_j71BYAQtsbrHc4M8,465
45
46
  nlbone/interfaces/api/exceptions.py,sha256=OczR1FND2nbCngwbfgaPrgDbDaz4Pc47mFSHgtL7tW8,313
46
47
  nlbone/interfaces/api/routers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
47
48
  nlbone/interfaces/api/schemas.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
49
+ nlbone/interfaces/api/dependencies/__init__.py,sha256=XrTGkHS8xqryfyr8XSm_s9sIzp4E0b44XQ40sVWcKMY,46
50
+ nlbone/interfaces/api/dependencies/db.py,sha256=IqDVq1lcCCxd22FBUg523lVANM_j71BYAQtsbrHc4M8,465
48
51
  nlbone/interfaces/api/pagination/__init__.py,sha256=fdTqy5efdYIcUWbK1mVPQMieGd3HV1lZ8vmIhhsuUKs,58
49
52
  nlbone/interfaces/api/pagination/offset_base.py,sha256=W0SJ0rHLMIqoyiPEAjnoKqY57LBXEyT5J-_5bS8r-NY,4535
50
53
  nlbone/interfaces/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -54,7 +57,7 @@ nlbone/interfaces/jobs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3
54
57
  nlbone/interfaces/jobs/sync_tokens.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
55
58
  nlbone/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
56
59
  nlbone/utils/time.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
57
- nlbone-0.1.29.dist-info/METADATA,sha256=px5zji1xoB5XO5m8WkVjgoBF7bZVtU1UQxkH-Fnx6zc,2256
58
- nlbone-0.1.29.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
59
- nlbone-0.1.29.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
60
- nlbone-0.1.29.dist-info/RECORD,,
60
+ nlbone-0.1.31.dist-info/METADATA,sha256=AQxSX36K4Z747tRRCrLWQ0qpuZyI586sVHKK00WAooo,2256
61
+ nlbone-0.1.31.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
62
+ nlbone-0.1.31.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
63
+ nlbone-0.1.31.dist-info/RECORD,,