Files
A guide on how to work with files using the WriftAI Python client
This section demonstrates common file operations you can perform with the WriftAI Python client. These examples are not exhaustive — check the client reference for all options.
Upload a file
files.upload takes a File, which wraps the file's contents along with an
optional mime_type. If provided, mime_type overrides any automatically
inferred value; if omitted, the MIME type is inferred from the file's name or
extension, falling back to application/octet-stream if it can't be determined.
Large files are automatically split into parts and uploaded concurrently, so you don't need to do anything differently for big files, just pass them the same way.
Upload from a file path
from pathlib import Path
from wriftai import File
upload_result = wriftai.files.upload(File(Path("report.pdf")))Upload raw bytes
There's no filename to infer from here, so this falls back
to application/octet-stream unless mime_type is provided:
from wriftai import File
upload_result = wriftai.files.upload(File(b"raw file contents"))File-like objects
Binary file objects work as content too:
from wriftai import File
with open("chart.png", "rb") as f:
upload_result = wriftai.files.upload(File(f))If the object has a name attribute, as file objects opened with open() do,
it's used for MIME type inference the same way a path's extension is.
Override the inferred MIME type
Pass mime_type explicitly to override the inferred or fallback value:
from wriftai import File
upload_result = wriftai.files.upload(
File(b"raw file contents", mime_type="application/pdf")
)Track upload progress
Pass on_progress to be notified as the upload proceeds. Each time a chunk
is sent, it's called with the number of bytes just sent and the total size
of the file.
from wriftai import File
def on_progress(bytes_delta: int, total_bytes: int) -> None:
print(f"sent {bytes_delta} of {total_bytes} bytes")
upload_result = wriftai.files.upload(
File(Path("report.pdf")), on_progress=on_progress
)on_progress may be called concurrently from multiple threads while parts
upload together, once per chunk sent. If it updates any shared state,
make sure that update is thread-safe.