open-agent-docs 0.3.0__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.
- open_agent_docs/__init__.py +86 -0
- open_agent_docs/_base_client.py +667 -0
- open_agent_docs/_client.py +112 -0
- open_agent_docs/_embed.py +83 -0
- open_agent_docs/_errors.py +206 -0
- open_agent_docs/_files.py +51 -0
- open_agent_docs/_generated/__init__.py +2 -0
- open_agent_docs/_generated/models.py +1378 -0
- open_agent_docs/_generated/resources.py +4300 -0
- open_agent_docs/_models.py +17 -0
- open_agent_docs/_pagination.py +132 -0
- open_agent_docs/_server.py +330 -0
- open_agent_docs/_sse.py +335 -0
- open_agent_docs/_types.py +35 -0
- open_agent_docs/_utils.py +15 -0
- open_agent_docs/_version.py +1 -0
- open_agent_docs/_webhook.py +85 -0
- open_agent_docs/py.typed +0 -0
- open_agent_docs/types.py +3 -0
- open_agent_docs-0.3.0.dist-info/METADATA +266 -0
- open_agent_docs-0.3.0.dist-info/RECORD +22 -0
- open_agent_docs-0.3.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Client 和 AsyncClient:方法一样,异步的全是 async(翻页、事件流除外,见各自的说明)。
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
import open_agent_docs as oad
|
|
5
|
+
|
|
6
|
+
client = oad.Client(base_url="https://docs.example.com", token="oad_…")
|
|
7
|
+
client = oad.Client() # 读环境变量 OAD_BASE_URL、OAD_TOKEN
|
|
8
|
+
ws = client.default_workspace()
|
|
9
|
+
page = client.pages.create(ws, title="周报", markdown="# 本周\\n\\n- 上线了 SDK")
|
|
10
|
+
```
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Mapping, Optional
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from ._base_client import DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT
|
|
19
|
+
from ._generated.resources import AsyncResources, SyncResources
|
|
20
|
+
|
|
21
|
+
__all__ = ["Client", "AsyncClient"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Client(SyncResources):
|
|
25
|
+
"""同步客户端。
|
|
26
|
+
|
|
27
|
+
参数(都可以不给):
|
|
28
|
+
- base_url:服务器地址,默认环境变量 OAD_BASE_URL,再没有就 http://127.0.0.1:8848(/api/v1 由 SDK 拼)
|
|
29
|
+
- token:Agent token、会话令牌或 JWT(Authorization: Bearer),默认环境变量 OAD_TOKEN
|
|
30
|
+
- header_secret / jwt_secret:OAD_AUTH=header / jwt 的服务器,配合 with_user 替用户调
|
|
31
|
+
- jwt_issuer、jwt_audience、jwt_ttl:with_user 签 JWT 时写进去(ttl 默认 3600 秒)
|
|
32
|
+
- timeout:单个请求的超时(秒,默认 60;事件流只管连接)
|
|
33
|
+
- max_retries:429、502/503/504、连不上时重试几次(默认 2)
|
|
34
|
+
- locale:zh / en,服务器错误信息的语言
|
|
35
|
+
- headers:每个请求额外带的头
|
|
36
|
+
- http_client:自己的 httpx.Client(代理、证书之类)
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
*,
|
|
42
|
+
base_url: Optional[str] = None,
|
|
43
|
+
token: Optional[str] = None,
|
|
44
|
+
header_secret: Optional[str] = None,
|
|
45
|
+
jwt_secret: Optional[str] = None,
|
|
46
|
+
jwt_issuer: Optional[str] = None,
|
|
47
|
+
jwt_audience: Optional[str] = None,
|
|
48
|
+
jwt_ttl: int = 3600,
|
|
49
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
50
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
51
|
+
locale: Optional[str] = None,
|
|
52
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
53
|
+
http_client: Optional[httpx.Client] = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
super().__init__(
|
|
56
|
+
base_url=base_url,
|
|
57
|
+
token=token,
|
|
58
|
+
header_secret=header_secret,
|
|
59
|
+
jwt_secret=jwt_secret,
|
|
60
|
+
jwt_issuer=jwt_issuer,
|
|
61
|
+
jwt_audience=jwt_audience,
|
|
62
|
+
jwt_ttl=jwt_ttl,
|
|
63
|
+
timeout=timeout,
|
|
64
|
+
max_retries=max_retries,
|
|
65
|
+
locale=locale,
|
|
66
|
+
headers=headers,
|
|
67
|
+
http_client=http_client,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AsyncClient(AsyncResources):
|
|
72
|
+
"""异步客户端,参数和 Client 一样(http_client 是 httpx.AsyncClient)。
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
async with oad.AsyncClient() as client:
|
|
76
|
+
ws = await client.default_workspace()
|
|
77
|
+
page = await client.pages.create(ws, title="周报")
|
|
78
|
+
async for v in client.pages.versions.list(page.id): # 翻页:直接 async for
|
|
79
|
+
...
|
|
80
|
+
```
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
*,
|
|
86
|
+
base_url: Optional[str] = None,
|
|
87
|
+
token: Optional[str] = None,
|
|
88
|
+
header_secret: Optional[str] = None,
|
|
89
|
+
jwt_secret: Optional[str] = None,
|
|
90
|
+
jwt_issuer: Optional[str] = None,
|
|
91
|
+
jwt_audience: Optional[str] = None,
|
|
92
|
+
jwt_ttl: int = 3600,
|
|
93
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
94
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
95
|
+
locale: Optional[str] = None,
|
|
96
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
97
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
super().__init__(
|
|
100
|
+
base_url=base_url,
|
|
101
|
+
token=token,
|
|
102
|
+
header_secret=header_secret,
|
|
103
|
+
jwt_secret=jwt_secret,
|
|
104
|
+
jwt_issuer=jwt_issuer,
|
|
105
|
+
jwt_audience=jwt_audience,
|
|
106
|
+
jwt_ttl=jwt_ttl,
|
|
107
|
+
timeout=timeout,
|
|
108
|
+
max_retries=max_retries,
|
|
109
|
+
locale=locale,
|
|
110
|
+
headers=headers,
|
|
111
|
+
http_client=http_client,
|
|
112
|
+
)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""嵌入用的:sign_jwt(宿主替用户签 JWT,HS256,只用标准库)、embed_url(iframe 的地址)。"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any, Dict, Mapping, Optional, Sequence, Union
|
|
10
|
+
|
|
11
|
+
from ._utils import quote_path
|
|
12
|
+
|
|
13
|
+
__all__ = ["sign_jwt", "embed_url", "WorkspaceClaim"]
|
|
14
|
+
|
|
15
|
+
# 工作区 id,或者 {"id": ..., "role": ...}
|
|
16
|
+
WorkspaceClaim = Union[str, Mapping[str, Any]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _b64(b: bytes) -> str:
|
|
20
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _json(v: Any) -> bytes:
|
|
24
|
+
return json.dumps(v, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sign_jwt(
|
|
28
|
+
secret: Union[str, bytes],
|
|
29
|
+
user_id: str,
|
|
30
|
+
name: Optional[str] = None,
|
|
31
|
+
email: Optional[str] = None,
|
|
32
|
+
workspaces: Optional[Sequence[WorkspaceClaim]] = None,
|
|
33
|
+
ttl: int = 3600,
|
|
34
|
+
issuer: Optional[str] = None,
|
|
35
|
+
audience: Optional[str] = None,
|
|
36
|
+
now: Optional[float] = None,
|
|
37
|
+
) -> str:
|
|
38
|
+
"""签一个 HS256 的 JWT,给 OAD_AUTH=jwt 的服务器(OAD_JWT_SECRET 是同一个密钥)。
|
|
39
|
+
|
|
40
|
+
claims:sub、name、email、workspaces、iat、exp、iss、aud(没给的不写)。workspaces 是工作区 id 的数组,
|
|
41
|
+
或者 [{"id": ..., "role": "viewer"}];不给就进默认工作区。now 是“现在”(秒),测试用。
|
|
42
|
+
要 RS256 / ES256 的用自己的 JWT 库签,claims 照这个写。
|
|
43
|
+
"""
|
|
44
|
+
iat = int(time.time() if now is None else now)
|
|
45
|
+
claims: Dict[str, Any] = {"sub": user_id}
|
|
46
|
+
if name is not None:
|
|
47
|
+
claims["name"] = name
|
|
48
|
+
if email is not None:
|
|
49
|
+
claims["email"] = email
|
|
50
|
+
if workspaces is not None:
|
|
51
|
+
claims["workspaces"] = [w if isinstance(w, str) else dict(w) for w in workspaces]
|
|
52
|
+
claims["iat"] = iat
|
|
53
|
+
claims["exp"] = iat + int(ttl)
|
|
54
|
+
if issuer is not None:
|
|
55
|
+
claims["iss"] = issuer
|
|
56
|
+
if audience is not None:
|
|
57
|
+
claims["aud"] = audience
|
|
58
|
+
head = _b64(_json({"alg": "HS256", "typ": "JWT"}))
|
|
59
|
+
body = _b64(_json(claims))
|
|
60
|
+
key = secret.encode("utf-8") if isinstance(secret, str) else secret
|
|
61
|
+
sig = hmac.new(key, f"{head}.{body}".encode("ascii"), hashlib.sha256).digest()
|
|
62
|
+
return f"{head}.{body}.{_b64(sig)}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def embed_url(
|
|
66
|
+
base_url: str,
|
|
67
|
+
page_id: str,
|
|
68
|
+
theme: Optional[str] = None,
|
|
69
|
+
lang: Optional[str] = None,
|
|
70
|
+
token: Optional[str] = None,
|
|
71
|
+
) -> str:
|
|
72
|
+
"""iframe 里嵌一个页面的地址:`<base>/p/<page_id>?embed=1[&theme=][&lang=][#token=]`。
|
|
73
|
+
|
|
74
|
+
token(JWT)放在 # 后面:不进服务器日志、不进 Referer,网页读到后马上从地址栏抹掉。
|
|
75
|
+
"""
|
|
76
|
+
url = f"{base_url.rstrip('/')}/p/{quote_path(page_id)}?embed=1"
|
|
77
|
+
if theme:
|
|
78
|
+
url += "&theme=" + quote_path(theme)
|
|
79
|
+
if lang:
|
|
80
|
+
url += "&lang=" + quote_path(lang)
|
|
81
|
+
if token:
|
|
82
|
+
url += "#token=" + quote_path(token)
|
|
83
|
+
return url
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""错误。都从 OADError 派生:
|
|
2
|
+
|
|
3
|
+
- 服务器回了错误:APIError 和按状态码分的子类(NotFoundError……),带 status、code、message、request_id、retry_after
|
|
4
|
+
- 连不上、超时:APIConnectionError、APITimeoutError
|
|
5
|
+
- 配置不对:ConfigurationError;webhook 验签失败:WebhookVerificationError(kind)
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any, Dict, Optional, Type, cast
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"OADError",
|
|
16
|
+
"ConfigurationError",
|
|
17
|
+
"WebhookVerificationError",
|
|
18
|
+
"APIError",
|
|
19
|
+
"BadRequestError",
|
|
20
|
+
"AuthenticationError",
|
|
21
|
+
"PermissionDeniedError",
|
|
22
|
+
"NotFoundError",
|
|
23
|
+
"ConflictError",
|
|
24
|
+
"GoneError",
|
|
25
|
+
"TooLargeError",
|
|
26
|
+
"RateLimitError",
|
|
27
|
+
"InternalServerError",
|
|
28
|
+
"BadGatewayError",
|
|
29
|
+
"APIConnectionError",
|
|
30
|
+
"APITimeoutError",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class OADError(Exception):
|
|
35
|
+
"""这个包抛的所有错误的基类。"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConfigurationError(OADError):
|
|
39
|
+
"""配置不对(比如 with_user 时 header_secret 和 jwt_secret 都没配)。"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WebhookVerificationError(OADError):
|
|
43
|
+
"""webhook 验签失败。kind:signature(签名不对)/ stale(时间戳太旧或太新)/ malformed(缺头、格式不对)。"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, kind: str, message: str) -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.kind = kind
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class APIError(OADError):
|
|
51
|
+
"""服务器回了错误。code 是 `{ "error": { "code" } }` 里的(not_found……),不是 JSON 时是 http_<状态码>。"""
|
|
52
|
+
|
|
53
|
+
status: int
|
|
54
|
+
code: str
|
|
55
|
+
message: str
|
|
56
|
+
request_id: Optional[str]
|
|
57
|
+
retry_after: Optional[float]
|
|
58
|
+
response: Optional[httpx.Response]
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
status: int,
|
|
63
|
+
code: str,
|
|
64
|
+
message: str,
|
|
65
|
+
request_id: Optional[str] = None,
|
|
66
|
+
retry_after: Optional[float] = None,
|
|
67
|
+
*,
|
|
68
|
+
response: Optional[httpx.Response] = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
super().__init__(f"{status} {code}: {message}")
|
|
71
|
+
self.status = status
|
|
72
|
+
self.code = code
|
|
73
|
+
self.message = message
|
|
74
|
+
self.request_id = request_id
|
|
75
|
+
self.retry_after = retry_after
|
|
76
|
+
self.response = response
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def status_code(self) -> int:
|
|
80
|
+
"""同 status"""
|
|
81
|
+
return self.status
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class BadRequestError(APIError):
|
|
85
|
+
"""400"""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class AuthenticationError(APIError):
|
|
89
|
+
"""401:没登录、token 不对或过期"""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class PermissionDeniedError(APIError):
|
|
93
|
+
"""403:没权限"""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class NotFoundError(APIError):
|
|
97
|
+
"""404"""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ConflictError(APIError):
|
|
101
|
+
"""409:比如 base 版本对不上"""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class GoneError(APIError):
|
|
105
|
+
"""410:邀请过期之类"""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class TooLargeError(APIError):
|
|
109
|
+
"""413"""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class RateLimitError(APIError):
|
|
113
|
+
"""429:太快了;retry_after 是服务器让等的秒数"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class InternalServerError(APIError):
|
|
117
|
+
"""5xx"""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class BadGatewayError(InternalServerError):
|
|
121
|
+
"""502:服务器去外部网站取东西失败"""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class APIConnectionError(OADError):
|
|
125
|
+
"""连不上、连接被断。"""
|
|
126
|
+
|
|
127
|
+
def __init__(self, message: str = "连不上服务器", *, request: Optional[httpx.Request] = None) -> None:
|
|
128
|
+
super().__init__(message)
|
|
129
|
+
self.request = request
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class APITimeoutError(APIConnectionError):
|
|
133
|
+
"""超时。"""
|
|
134
|
+
|
|
135
|
+
def __init__(self, message: str = "请求超时", *, request: Optional[httpx.Request] = None) -> None:
|
|
136
|
+
super().__init__(message, request=request)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
_BY_STATUS: Dict[int, Type[APIError]] = {
|
|
140
|
+
400: BadRequestError,
|
|
141
|
+
401: AuthenticationError,
|
|
142
|
+
403: PermissionDeniedError,
|
|
143
|
+
404: NotFoundError,
|
|
144
|
+
409: ConflictError,
|
|
145
|
+
410: GoneError,
|
|
146
|
+
413: TooLargeError,
|
|
147
|
+
429: RateLimitError,
|
|
148
|
+
502: BadGatewayError,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_retry_after(v: Optional[str]) -> Optional[float]:
|
|
153
|
+
"""Retry-After:秒数(HTTP 日期的写法也认)。"""
|
|
154
|
+
if not v:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
return max(0.0, float(v.strip()))
|
|
158
|
+
except ValueError:
|
|
159
|
+
pass
|
|
160
|
+
try:
|
|
161
|
+
import email.utils
|
|
162
|
+
import time
|
|
163
|
+
|
|
164
|
+
t = email.utils.parsedate_to_datetime(v)
|
|
165
|
+
return max(0.0, t.timestamp() - time.time())
|
|
166
|
+
except (TypeError, ValueError, IndexError):
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def error_from_response(resp: httpx.Response) -> APIError:
|
|
171
|
+
"""响应(已经读完)→ 对应的错误。"""
|
|
172
|
+
status = resp.status_code
|
|
173
|
+
code = f"http_{status}"
|
|
174
|
+
message = ""
|
|
175
|
+
try:
|
|
176
|
+
body: Any = json.loads(resp.content)
|
|
177
|
+
except ValueError:
|
|
178
|
+
body = None
|
|
179
|
+
if isinstance(body, dict):
|
|
180
|
+
err: Any = cast(Dict[str, Any], body).get("error")
|
|
181
|
+
if isinstance(err, dict):
|
|
182
|
+
e = cast(Dict[str, Any], err)
|
|
183
|
+
c: Any = e.get("code")
|
|
184
|
+
m: Any = e.get("message")
|
|
185
|
+
if isinstance(c, str) and c:
|
|
186
|
+
code = c
|
|
187
|
+
if isinstance(m, str):
|
|
188
|
+
message = m
|
|
189
|
+
elif isinstance(err, str):
|
|
190
|
+
message = err
|
|
191
|
+
if not message:
|
|
192
|
+
try:
|
|
193
|
+
message = resp.text.strip()[:500]
|
|
194
|
+
except Exception: # noqa: BLE001
|
|
195
|
+
message = ""
|
|
196
|
+
if not message:
|
|
197
|
+
message = resp.reason_phrase or f"HTTP {status}"
|
|
198
|
+
cls = _BY_STATUS.get(status) or (InternalServerError if status >= 500 else APIError)
|
|
199
|
+
return cls(
|
|
200
|
+
status,
|
|
201
|
+
code,
|
|
202
|
+
message,
|
|
203
|
+
request_id=resp.headers.get("x-request-id"),
|
|
204
|
+
retry_after=parse_retry_after(resp.headers.get("retry-after")),
|
|
205
|
+
response=resp,
|
|
206
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""上传:files.upload 的 file 可以是 bytes、路径(pathlib.Path)、打开的文件,或者 (文件名, bytes | 文件对象[, 类型])。"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import mimetypes
|
|
5
|
+
import os
|
|
6
|
+
from typing import IO, Dict, Optional, Tuple, Union
|
|
7
|
+
|
|
8
|
+
__all__ = ["FileTypes", "file_part", "csv_body"]
|
|
9
|
+
|
|
10
|
+
FileContent = Union[bytes, IO[bytes]]
|
|
11
|
+
FileTypes = Union[
|
|
12
|
+
bytes,
|
|
13
|
+
"os.PathLike[str]",
|
|
14
|
+
IO[bytes],
|
|
15
|
+
Tuple[str, FileContent],
|
|
16
|
+
Tuple[str, FileContent, str],
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read(c: FileContent) -> bytes:
|
|
21
|
+
# 先读成 bytes:重试时还能再发一次
|
|
22
|
+
return c if isinstance(c, bytes) else c.read()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def file_part(file: FileTypes, filename: Optional[str] = None, content_type: Optional[str] = None) -> Dict[str, Tuple[str, bytes, str]]:
|
|
26
|
+
"""→ httpx 的 files(multipart 的 file 字段)"""
|
|
27
|
+
name: str
|
|
28
|
+
data: bytes
|
|
29
|
+
ctype = content_type
|
|
30
|
+
if isinstance(file, bytes):
|
|
31
|
+
name, data = filename or "file", file
|
|
32
|
+
elif isinstance(file, tuple):
|
|
33
|
+
name, data = file[0], _read(file[1])
|
|
34
|
+
if len(file) == 3 and not ctype:
|
|
35
|
+
ctype = file[2]
|
|
36
|
+
name = filename or name
|
|
37
|
+
elif isinstance(file, os.PathLike):
|
|
38
|
+
path = os.fspath(file)
|
|
39
|
+
with open(path, "rb") as f:
|
|
40
|
+
data = f.read()
|
|
41
|
+
name = filename or os.path.basename(path)
|
|
42
|
+
else:
|
|
43
|
+
data = file.read()
|
|
44
|
+
name = filename or os.path.basename(str(getattr(file, "name", "") or "")) or "file"
|
|
45
|
+
if not ctype:
|
|
46
|
+
ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
47
|
+
return {"file": (name, data, ctype)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def csv_body(csv: Union[str, bytes]) -> bytes:
|
|
51
|
+
return csv.encode("utf-8") if isinstance(csv, str) else csv
|