superfaktura_api: add download method for save IO[bytes] data stream

This commit is contained in:
Richard Kubíček
2025-03-04 13:40:40 +01:00
parent bb6b6343b0
commit 8d5bf14be3
3 changed files with 54 additions and 12 deletions

View File

@@ -24,7 +24,7 @@ Usage:
"""
import os
from typing import Dict
from typing import Dict, IO
import requests
from dotenv import load_dotenv # type: ignore
@@ -97,6 +97,48 @@ class SuperFakturaAPI:
f"Get status code: {req.status_code}; {req.content!r}"
)
def download(self, endpoint: str, descriptor: IO[bytes], timeout: int = 5) -> None:
"""
Download data stream from the SuperFaktura API.
Download data stream from the specified endpoint in the SuperFaktura API.
Args:
endpoint (str): The API endpoint to retrieve data from (e.g. 'invoices', 'clients',
etc.).
descriptor (IO[bytes]): The descriptor to write the data stream to.
timeout (int, optional): The timeout for the API request in seconds. Defaults to 5.
Returns:
None
Raises:
SuperFakturaAPIException: If the API request fails or returns an error.
Examples:
>>> from superfaktura.invoice import Invoice
>>> from superfaktura.enumerations.language import Language
>>> invoice = Invoice()
>>> with open("invoice.pdf", "wb") as f:
>>> invoice.get_pdf(invoice=invoice_data, descriptor=f, language=Language.English)
Notes:
The available endpoints can be found in the SuperFaktura API documentation.
"""
url = f"{self._api_url}/{endpoint}"
req = requests.get(url=url, headers=self._auth_header, timeout=timeout)
if req.status_code == 200:
if descriptor.writable():
descriptor.write(req.content)
else:
raise SuperFakturaAPIException(
f"Descriptor {descriptor} is not writable"
)
else:
raise SuperFakturaAPIException(
f"Download status code: {req.status_code}; {req.content!r}"
)
def post(self, endpoint: str, data: str, timeout: int = 5) -> Dict:
"""
Creates or updates data in the SuperFaktura API.