|
3 | 3 | import logging |
4 | 4 | import os |
5 | 5 | import time |
| 6 | +import anyio |
6 | 7 |
|
7 | 8 | from .config import settings, reload_settings |
8 | 9 |
|
@@ -80,7 +81,9 @@ async def upload_file(self, file_path: str) -> int: |
80 | 81 | url = f"{base}/projects/{self.project_id}/files" |
81 | 82 | try: |
82 | 83 | async with httpx.AsyncClient(timeout=60.0) as client: |
83 | | - files = {"file": (os.path.basename(file_path), open(file_path, "rb"), "application/pdf")} |
| 84 | + async with await anyio.open_file(file_path, 'rb') as f: |
| 85 | + content = await f.read() |
| 86 | + files = {"file": (os.path.basename(file_path), content, "application/pdf")} |
84 | 87 | if self._use_oauth(): |
85 | 88 | try: |
86 | 89 | token = await self.get_access_token() |
@@ -154,20 +157,21 @@ async def send_fax_file(self, to_number: str, file_path: str) -> Dict[str, Any]: |
154 | 157 | to = f"+{digits}" |
155 | 158 | url = f"{self.base_url}/projects/{self.project_id}/faxes" |
156 | 159 | async with httpx.AsyncClient(timeout=60.0) as client: |
157 | | - # httpx expects a mapping of field name → (filename, fileobj, content_type) |
| 160 | + # httpx expects a mapping of field name → (filename, bytes, content_type) |
158 | 161 | # For the additional text field, pass as data not files |
159 | | - with open(file_path, "rb") as fh: |
160 | | - files = {"file": (os.path.basename(file_path), fh, "application/pdf")} |
161 | | - data = {"to": to} |
162 | | - if self._use_oauth(): |
163 | | - try: |
164 | | - token = await self.get_access_token() |
165 | | - resp = await client.post(url, files=files, data=data, headers={"Authorization": f"Bearer {token}"}) |
166 | | - except Exception as e: |
167 | | - logger.warning("Sinch OAuth send_fax_file failed; falling back to Basic: %s", e) |
168 | | - resp = await client.post(url, files=files, data=data, auth=self._basic_auth()) |
169 | | - else: |
| 162 | + async with await anyio.open_file(file_path, 'rb') as fh: |
| 163 | + content = await fh.read() |
| 164 | + files = {"file": (os.path.basename(file_path), content, "application/pdf")} |
| 165 | + data = {"to": to} |
| 166 | + if self._use_oauth(): |
| 167 | + try: |
| 168 | + token = await self.get_access_token() |
| 169 | + resp = await client.post(url, files=files, data=data, headers={"Authorization": f"Bearer {token}"}) |
| 170 | + except Exception as e: |
| 171 | + logger.warning("Sinch OAuth send_fax_file failed; falling back to Basic: %s", e) |
170 | 172 | resp = await client.post(url, files=files, data=data, auth=self._basic_auth()) |
| 173 | + else: |
| 174 | + resp = await client.post(url, files=files, data=data, auth=self._basic_auth()) |
171 | 175 | if resp.status_code >= 400: |
172 | 176 | raise RuntimeError(f"Sinch create fax error {resp.status_code}: {resp.text}") |
173 | 177 | return resp.json() |
|
0 commit comments