tempest_fastapi_sdk.spreadsheet¶
Geração de planilhas .xlsx que o destinatário consegue usar.
SheetWriter
¶
SheetWriter(
sheet: Worksheet,
columns: Sequence[Column] = (),
*,
style: SheetStyle = DEFAULT_SHEET_STYLE,
start_row: int = 1,
)
Append rows to a worksheet, styled from column specs and a theme.
Stateful in exactly one respect — :attr:row, the next free row — so
two writers may share a workbook but never a sheet.
Attributes:
| Name | Type | Description |
|---|---|---|
sheet |
Worksheet
|
The worksheet being written. |
columns |
tuple[Column, ...]
|
Column specifications, left to right. |
style |
SheetStyle
|
The theme applied to headers, groups and totals. |
row |
int
|
The next free row, 1-based. Assign to it to jump. |
Bind a writer to a worksheet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sheet
|
Worksheet
|
The sheet to write into. |
required |
columns
|
Sequence[Column]
|
Column specifications, left to right. May be empty when the sheet is a free-form block of label/value rows rather than a table. |
()
|
style
|
SheetStyle
|
Colours and sizes for emphasised rows. |
DEFAULT_SHEET_STYLE
|
start_row
|
int
|
First row to write, 1-based. |
1
|
column_count
property
¶
How many columns the sheet spans.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of declared columns, or |
int
|
declared — a title block still has to merge across something. |
title_block
¶
Write centred, merged title lines across the table width.
The identification block a formal document opens with: issuing body,
process number, subject. Each line is merged across span
columns, so the block stays centred when a column is added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Sequence[str]
|
One string per line, top to bottom. Empty strings are written as empty merged rows, which is how a caller leaves deliberate breathing room inside the block. |
required |
span
|
int | None
|
How many columns to merge across. Defaults to
:attr: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
header_row
¶
Write the styled column-header row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
titles
|
Sequence[str] | None
|
Header texts. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
write_row
¶
write_row(
values: Sequence[CellValue],
*,
formats: Sequence[str | None] | None = None,
bold: bool = False,
background: str | None = None,
border: bool = True,
) -> int
Write one body row, applying each column's format and alignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[CellValue]
|
Cell values, left to right. A
value of |
required |
formats
|
Sequence[str | None] | None
|
Per-cell number formats overriding the column's, for the row where one cell holds a percentage in an otherwise monetary column. |
None
|
bold
|
bool
|
Whether to bold the row. |
False
|
background
|
str | None
|
Hex fill for the whole row. |
None
|
border
|
bool
|
Whether to draw the thin grid around the cells. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
group_row
¶
group_row(values: Sequence[CellValue]) -> int
Write a section heading inside the table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[CellValue]
|
Cell values, usually just the group label in the first column. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
total_row
¶
total_row(values: Sequence[CellValue]) -> int
Write an emphasised total row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[CellValue]
|
Cell values, usually a label and one or more amounts. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
blank_rows
¶
Advance the cursor past empty rows, writing nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
How many rows to skip. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The next free row. |
apply_widths
¶
Set the width of every column that declared one.
Call it once, after the rows are written or before — widths are a property of the column, not of the content.
freeze_below
¶
Freeze every row above row so headers survive scrolling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
int | None
|
First scrolling row. |
None
|
Column
dataclass
¶
Column(
title: str,
width: int | None = None,
number_format: str | None = None,
horizontal: str | None = None,
wrap: bool = False,
)
Specification of one column: its header, width and cell treatment.
Declared once and reused for every row, so a column's number format cannot drift between the first row and the thousandth.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
Header text. |
width |
int | None
|
Column width in characters. |
number_format |
str | None
|
Excel number format applied to every
body cell of this column — see
:mod: |
horizontal |
str | None
|
Horizontal alignment ( |
wrap |
bool
|
Whether body cells wrap their text. Turn it on for the description column and leave it off elsewhere: a wrapped short cell is what makes a row unnecessarily tall. |
CellValue
module-attribute
¶
CellValue = str | int | float | Decimal | date | datetime | Formula | None
What a cell may receive.
Narrower than what openpyxl accepts (it also takes bytes and rich
text) and deliberately so — widening it to object is what lets an
unconverted domain object reach a cell and land in the file as its
repr.
A str is written as text, whatever its first character; a
:class:Formula is written as a live formula. Before this split, any
str starting with = became a formula, which made every exported
user-controlled string a formula-injection vector.
Formula
dataclass
¶
A live formula, written to the cell as one.
A plain str is always written as text, even when it starts with
=: the value usually comes from a user, a database row or an import,
and openpyxl would otherwise turn =HYPERLINK("https://...") typed
into a name field into a live formula in every exported file. Wrapping
the expression is how the code that builds a closing check says "this
one is mine".
Attributes:
| Name | Type | Description |
|---|---|---|
expression |
str
|
The formula, starting with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
new_workbook
¶
Create a workbook holding exactly the named sheets.
openpyxl always creates a workbook with one sheet called Sheet.
Forgetting to remove it ships a document with a stray empty tab, which
is the kind of detail that makes a generated file look generated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*sheet_titles
|
str
|
Sheet names, in tab order. Passing none returns a workbook with the default sheet untouched. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
Workbook |
Workbook
|
The workbook, with the sheets created and the default one |
Workbook
|
removed when titles were given. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
workbook_to_bytes
¶
Serialize a workbook to .xlsx bytes in memory.
Keeps the file off disk, which is what lets a handler stream it as a download or hand it to object storage without a temporary path to clean up (and without a race between two requests writing the same one).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workbook
|
Workbook
|
The workbook to serialize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The |
SheetStyle
dataclass
¶
SheetStyle(
title_size: int = 12,
header_background: str = "1F3864",
header_foreground: str = "FFFFFF",
header_size: int = 10,
group_background: str = "D9E2F3",
total_background: str = "FFF2CC",
border_color: str = "BFBFBF",
font_name: str | None = None,
)
Colours, sizes and emphasis for the rows a writer produces.
Attributes:
| Name | Type | Description |
|---|---|---|
title_size |
int
|
Point size of the merged title block. |
header_background |
str
|
Fill behind the column-header row. |
header_foreground |
str
|
Text colour of the column-header row. |
header_size |
int
|
Point size of header and body text. |
group_background |
str
|
Fill behind a section/group row — a subheading inside the table rather than above it. |
total_background |
str
|
Fill behind a total row, the line a reader looks for first. |
border_color |
str
|
Colour of the thin grid drawn around cells. |
font_name |
str | None
|
Typeface for every cell. |
DEFAULT_SHEET_STYLE
module-attribute
¶
DEFAULT_SHEET_STYLE: SheetStyle = SheetStyle()
The theme used when a writer is built without one.
Dark navy header with white text, pale blue group rows, pale amber totals — legible in print and in grayscale, which is how a document submitted to a public body is often read.
BR_CURRENCY_FORMAT
module-attribute
¶
Real with symbol, pinned to pt-BR: R$ 1.234,56.
The leading [$-416] language code is what survives the file being
opened under another locale; the symbol is a quoted literal. The
currency-tagged [$R$-416] #,##0.00 looks equivalent and is not:
LibreOffice 7.4 renders it R$ 1,234.56 under en-US. Dropping the code
to "R$ #,##0.00" keeps the symbol and loses the separators the same way.
BR_CURRENCY_FORMAT_NO_SYMBOL
module-attribute
¶
Real without the symbol: 1.234,56.
For a column whose header already says (R$) and that would otherwise
repeat the symbol on every one of a thousand rows.
BR_QUANTITY_FORMAT
module-attribute
¶
Non-monetary quantity with two decimals: 1.234,56.
BR_INTEGER_FORMAT
module-attribute
¶
Whole number with thousands grouping: 1.234.
BR_PERCENT_FORMAT
module-attribute
¶
Percentage with two decimals: 30,00%.
The [$-416] prefix pins the decimal comma. Without it the mask follows
the reader's locale: LibreOffice renders a plain 0.00% as 30.00%
under en-US and 30,00 % under de-DE.
Excel multiplies by 100 itself, so the cell must hold the ratio
(0.30), never the percentage (30). Writing 30 into a percent-format
cell displays 3000,00% — a mistake that reads as a typo but is a unit
error.
BR_DATE_FORMAT
module-attribute
¶
Date as a Brazilian document writes it: 14/08/2026.
The / in a date mask is the locale's date separator, not a literal
slash, so without [$-416] a de-DE reader sees 14.08.2026. The
language code pins the slash.
BR_DATETIME_FORMAT
module-attribute
¶
Date and time, 24-hour: 14/08/2026 19:30.
Pinned with [$-416] for the same reason as :data:BR_DATE_FORMAT.
TEXT_FORMAT
module-attribute
¶
Force a cell to be read as text.
The escape hatch for identifiers that look numeric and must not be
normalized: a CPF with leading zeros, a process number like 0001/2026,
a bank branch. Without it Excel drops the zeros and there is no way back.
read_google_sheet
async
¶
read_google_sheet(
url: str,
*,
client: AsyncClient | None = None,
timeout: float = 30.0,
max_bytes: int | None = DEFAULT_GOOGLE_CSV_MAX_DOWNLOAD_BYTES,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
) -> list[dict[str, str]]
Read one tab of a publicly shared Google Sheet as a list of rows.
Each row is a dict keyed by the header row, every value a str
exactly as the CSV export renders it — an empty cell is "". Blank
rows are skipped. A sheet with only a header, or nothing at all,
returns [].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The shared link (any shape
:func: |
required |
client
|
AsyncClient | None
|
Client to reuse. The reader
never closes an injected client. |
None
|
timeout
|
float
|
Seconds the created client waits for the export.
Ignored when |
30.0
|
max_bytes
|
int | None
|
Most bytes the CSV export may answer
with; the body is streamed and the transfer stops past it.
Defaults to :data: |
DEFAULT_GOOGLE_CSV_MAX_DOWNLOAD_BYTES
|
max_rows
|
int | None
|
Most data rows (blank ones excluded) the tab
may hold, counted while the CSV is parsed. Defaults to
:data: |
DEFAULT_XLSX_MAX_ROWS
|
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
list[dict[str, str]]: The data rows, in sheet order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
GoogleSheetAccessError
|
If the export does not answer with CSV —
the sheet does not exist, is not shared as Anyone with the
link, or the |
SpreadsheetTooLargeError
|
If the download passes |
HTTPError
|
If the request itself fails. |
read_google_sheet_as
async
¶
read_google_sheet_as(
url: str,
schema: type[ModelT],
*,
client: AsyncClient | None = None,
timeout: float = 30.0,
omit_blank: bool = True,
max_bytes: int | None = DEFAULT_GOOGLE_CSV_MAX_DOWNLOAD_BYTES,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
) -> list[ModelT]
Read one tab of a public Google Sheet and validate each row.
The header names are the keys handed to schema.model_validate, so
a column maps to the field of the same name (use
validation_alias for a header that is not a valid identifier).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The shared link or the bare ID; see
:func: |
required |
schema
|
type[ModelT]
|
The Pydantic model each row validates into. |
required |
client
|
AsyncClient | None
|
Client to reuse; never closed
by the reader. |
None
|
timeout
|
float
|
Seconds the created client waits. Ignored when
|
30.0
|
omit_blank
|
bool
|
Drop empty cells from the row before
validating, so a blank cell means absent: the field falls
back to its default, and a required field reports |
True
|
max_bytes
|
int | None
|
Most bytes the CSV export may answer
with; the body is streamed and the transfer stops past it.
Defaults to :data: |
DEFAULT_GOOGLE_CSV_MAX_DOWNLOAD_BYTES
|
max_rows
|
int | None
|
Most data rows (blank ones excluded) the tab
may hold, counted while the CSV is parsed. Defaults to
:data: |
DEFAULT_XLSX_MAX_ROWS
|
Returns:
| Type | Description |
|---|---|
list[ModelT]
|
list[ModelT]: One instance per data row, in sheet order. |
list[ModelT]
|
when the sheet has no data row. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
GoogleSheetAccessError
|
If the export does not answer with CSV. |
SpreadsheetTooLargeError
|
If the download passes |
GoogleSheetRowError
|
On the first row that fails validation;
|
HTTPError
|
If the request itself fails. |
google_sheet_export_url
¶
Build the export URL of a Google Sheet from the link a user shares.
Accepts the shapes a link takes in practice: the /edit link with
?usp=sharing, with the tab in ?gid= or in the #gid=
fragment, without /edit, under /u/<n>/ (multi-account), with
or without the scheme — or the bare spreadsheet ID. The tab is kept
when the link names one; without a gid the export URL leaves the
choice of tab to Google.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The shared link, or the bare spreadsheet ID. |
required |
export_format
|
Literal['csv', 'xlsx']
|
Format the export answers
with. |
'csv'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
followed by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
GoogleSheetAccessError
¶
GoogleSheetAccessError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: AppException
The export URL did not answer with the requested document.
Covers every way a readable sheet fails to come back: a link to a sheet
that does not exist, a gid that names no tab, a sheet not shared
as Anyone with the link, an upstream outage. Google answers those
with an HTML page rather than a distinct status, so the class does not
try to tell them apart — details carries the status_code and
content_type that were actually received, for whoever debugs it.
The status is 502: from the point of view of the API that calls
the reader, an upstream refused to hand over the data.
GoogleSheetRowError
¶
GoogleSheetRowError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: SpreadsheetRowError
One row of the sheet did not validate against the target model.
details["row"] is the row number as the spreadsheet shows it — the
header is row 1, so the first data row is row 2 — and
details["errors"] is Pydantic's error list for that row, without
the url and ctx keys (ctx may hold the raised exception,
which does not serialize to JSON).
A subclass of
:class:~tempest_fastapi_sdk.spreadsheet.reader.SpreadsheetRowError,
so except SpreadsheetRowError covers the CSV and the .xlsx
readers alike.
download_google_sheet_xlsx
async
¶
download_google_sheet_xlsx(
url: str,
*,
client: AsyncClient | None = None,
timeout: float = 30.0,
max_bytes: int | None = DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES,
) -> bytes
Download a public Google Sheet as one .xlsx workbook.
Every tab comes in the one request. The link's gid is dropped on
purpose: with it, the .xlsx export narrows to that single tab
(measured). Hand the bytes to
:func:~tempest_fastapi_sdk.spreadsheet.reader.read_xlsx,
:func:~tempest_fastapi_sdk.spreadsheet.reader.read_xlsx_as or
:func:~tempest_fastapi_sdk.spreadsheet.reader.read_xlsx_sheets to
read as many tabs as needed without downloading again. Needs no extra
by itself; reading the bytes does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The shared link (any shape
:func: |
required |
client
|
AsyncClient | None
|
Client to reuse. The reader
never closes an injected client. |
None
|
timeout
|
float
|
Seconds the created client waits for the export.
Ignored when |
30.0
|
max_bytes
|
int | None
|
Most bytes the export may answer with; the
body is streamed and the transfer stops past it. Defaults to
:data: |
DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
GoogleSheetAccessError
|
If the export does not answer with a
successful |
SpreadsheetTooLargeError
|
If the body passes |
HTTPError
|
If the request itself fails. |
read_google_sheet_xlsx
async
¶
read_google_sheet_xlsx(
url: str,
*,
client: AsyncClient | None = None,
timeout: float = 30.0,
max_bytes: int | None = DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
) -> dict[str, list[dict[str, XlsxCellValue]]]
Read every tab of a public Google Sheet in one request, by tab name.
Downloads with :func:download_google_sheet_xlsx and parses with
:func:~tempest_fastapi_sdk.spreadsheet.reader.read_xlsx_sheets_async,
in a worker thread behind its semaphore: each
row is a dict keyed by the tab's header row, and each cell keeps
its type — number, datetime, bool or str; an empty cell is
None. A formula reads as the value Google computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The shared link or the bare ID. A |
required |
client
|
AsyncClient | None
|
Client to reuse; never closed
by the reader. |
None
|
timeout
|
float
|
Seconds the created client waits. Ignored when
|
30.0
|
max_bytes
|
int | None
|
Most bytes the export may answer with.
Defaults to :data: |
DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES
|
max_rows
|
int | None
|
Most data rows each tab may hold. Defaults
to :data: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
Most bytes the workbook may
decompress to. Defaults to
:data: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
Highest decompressed-to-
compressed ratio for a part of at least 1 MiB. Defaults to
:data: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
Returns:
| Type | Description |
|---|---|
dict[str, list[dict[str, XlsxCellValue]]]
|
dict[str, list[dict[str, XlsxCellValue]]]: The rows of each tab, in |
dict[str, list[dict[str, XlsxCellValue]]]
|
tab order. Tab names are kept verbatim, trailing spaces included. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If |
GoogleSheetAccessError
|
If the export does not answer with an
|
SpreadsheetTooLargeError
|
If the download or the workbook passes a limit. |
HTTPError
|
If the request itself fails. |
DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES
module-attribute
¶
Bytes the .xlsx export may answer with before the download stops (32 MiB).
The body is streamed and counted; past the limit the transfer is closed and
:class:~tempest_fastapi_sdk.spreadsheet.reader.SpreadsheetTooLargeError
is raised, so at most this much is ever held.
The arithmetic: a workbook the reader accepts decompresses to at most
:data:~tempest_fastapi_sdk.spreadsheet.reader.DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
(100 MiB). Measured workbooks compress 7.2 to 8.1 times, so one at that
limit downloads as about 14 MiB; 32 MiB still admits it when it compresses
only 3.2 times, and anything larger would be refused by the decompressed
limit anyway. The 16-tab public sheet measured downloads as 785 152 bytes.
DEFAULT_GOOGLE_CSV_MAX_DOWNLOAD_BYTES
module-attribute
¶
Bytes the CSV export of one tab may answer with before the download stops (10 MiB).
Smaller than :data:DEFAULT_GOOGLE_SHEET_MAX_DOWNLOAD_BYTES because a byte
of CSV costs more memory than a byte of .xlsx: the CSV is not
compressed, and every cell becomes a str in a dict.
The arithmetic, measured on CPython 3.11 (peak RSS over the interpreter's
baseline, body included, parse only, three runs per file, spread under
0.5 MB): the 8-column tab the .xlsx limits were measured with (id, two
texts, three numbers, a date, a status) costs ~94 bytes of CSV and
~1 014 bytes of RSS per row, about 11 bytes of memory per byte of
CSV — 100 000 rows are 9 212 287 bytes and peaked at 96.7 MB. So a tab of
:data:~tempest_fastapi_sdk.spreadsheet.reader.DEFAULT_XLSX_MAX_ROWS rows
in that shape fits under this limit, and for it the row limit trips first:
110 000 rows (10 166 854 bytes) were refused at row 100 001. The worst case
is a tab of many two-character cells, ~31.5 bytes of memory per byte:
100 000 rows of 34 such cells (10 300 127 bytes) peaked at 309.4 MB over
the baseline. The largest tab of the 16-tab public sheet measured is
18 577 bytes.
read_xlsx
¶
read_xlsx(
source: XlsxSource,
*,
sheet: str | int = 0,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
) -> list[dict[str, XlsxCellValue]]
Read one tab of an .xlsx workbook as a list of rows.
Row 1 is the header; each later row is a dict keyed by it, each
value an :data:XlsxCellValue — an empty cell is None. Blank rows
are skipped. A tab with only a header, or nothing at all, returns
[]. Merged cells keep the value in their top-left cell only; the
rest of the range reads None.
The three limits are checked before the work they protect, and a
workbook over one is refused, never read in part. Raise them, or pass
None, for a file you trust.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. |
required |
sheet
|
str | int
|
The tab's name, or its 0-based position in tab order. Defaults to the first tab. |
0
|
max_rows
|
int | None
|
Most data rows (blank ones excluded) the tab
may hold. Defaults to :data: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
Most bytes the workbook's parts
may add up to once decompressed. Defaults to
:data: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
Highest decompressed-to-
compressed ratio for a part of at least 1 MiB. Defaults to
:data: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
Returns:
| Type | Description |
|---|---|
list[dict[str, XlsxCellValue]]
|
list[dict[str, XlsxCellValue]]: The data rows, in sheet order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
SheetNotFoundError
|
If the workbook has no such tab. |
FileNotFoundError
|
If a path does not exist. |
read_xlsx_as
¶
read_xlsx_as(
source: XlsxSource,
schema: type[ModelT],
*,
sheet: str | int = 0,
omit_blank: bool = True,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
) -> list[ModelT]
Read one tab of an .xlsx workbook and validate each row.
The header names are the keys handed to schema.model_validate, so
a column maps to the field of the same name (use
validation_alias for a header that is not a valid identifier).
Cells arrive typed (:data:XlsxCellValue), so a currency column
validates into float or Decimal without undoing any formatting.
The limits are those of :func:read_xlsx, checked before any row is
validated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. |
required |
schema
|
type[ModelT]
|
The Pydantic model each row validates into. |
required |
sheet
|
str | int
|
The tab's name, or its 0-based position. Defaults to the first tab. |
0
|
omit_blank
|
bool
|
Drop empty cells from the row before
validating, so a blank cell means absent: the field falls
back to its default, and a required field reports |
True
|
max_rows
|
int | None
|
Most data rows the tab may hold. Defaults to
:data: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
Most bytes the workbook may
decompress to. Defaults to
:data: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
Highest decompressed-to-
compressed ratio for a part of at least 1 MiB. Defaults to
:data: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
Returns:
| Type | Description |
|---|---|
list[ModelT]
|
list[ModelT]: One instance per data row, in sheet order. |
list[ModelT]
|
when the tab has no data row. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
SheetNotFoundError
|
If the workbook has no such tab. |
SpreadsheetRowError
|
On the first row that fails validation;
|
FileNotFoundError
|
If a path does not exist. |
read_xlsx_sheets
¶
read_xlsx_sheets(
source: XlsxSource,
*,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
) -> dict[str, list[dict[str, XlsxCellValue]]]
Read every tab of an .xlsx workbook, keyed by tab name.
Each tab follows the rules of :func:read_xlsx. Chart sheets, which
hold no cells, are left out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. |
required |
max_rows
|
int | None
|
Most data rows each tab may hold. The
workbook as a whole is bounded by |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
Most bytes the workbook's parts
may add up to once decompressed. Defaults to
:data: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
Highest decompressed-to-
compressed ratio for a part of at least 1 MiB. Defaults to
:data: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
Returns:
| Type | Description |
|---|---|
dict[str, list[dict[str, XlsxCellValue]]]
|
dict[str, list[dict[str, XlsxCellValue]]]: The rows of each tab, in |
dict[str, list[dict[str, XlsxCellValue]]]
|
tab order. An empty tab maps to |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
FileNotFoundError
|
If a path does not exist. |
read_xlsx_async
async
¶
read_xlsx_async(
source: XlsxSource,
*,
sheet: str | int = 0,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
semaphore: Semaphore | None = None,
) -> list[dict[str, XlsxCellValue]]
Read one tab of an .xlsx workbook without blocking the event loop.
:func:read_xlsx in a worker thread, behind a semaphore. The parse is
CPU-bound and takes seconds on a large tab, so calling the synchronous
reader from a coroutine — an upload endpoint — stops every other
request of the worker for that long. This is the one to await.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. A file object is read from the worker thread. |
required |
sheet
|
str | int
|
The tab's name, or its 0-based position. |
0
|
max_rows
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
As in :func: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
semaphore
|
Semaphore | None
|
Bounds how many reads run at
once. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, XlsxCellValue]]
|
list[dict[str, XlsxCellValue]]: The data rows, in sheet order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
SheetNotFoundError
|
If the workbook has no such tab. |
FileNotFoundError
|
If a path does not exist. |
read_xlsx_as_async
async
¶
read_xlsx_as_async(
source: XlsxSource,
schema: type[ModelT],
*,
sheet: str | int = 0,
omit_blank: bool = True,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
semaphore: Semaphore | None = None,
) -> list[ModelT]
Read one tab and validate each row without blocking the event loop.
:func:read_xlsx_as in a worker thread — the parse and the row
validation both run there — behind the same semaphore as
:func:read_xlsx_async.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. A file object is read from the worker thread. |
required |
schema
|
type[ModelT]
|
The Pydantic model each row validates into. |
required |
sheet
|
str | int
|
The tab's name, or its 0-based position. |
0
|
omit_blank
|
bool
|
As in :func: |
True
|
max_rows
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
As in :func: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
semaphore
|
Semaphore | None
|
Bounds how many reads run at
once. |
None
|
Returns:
| Type | Description |
|---|---|
list[ModelT]
|
list[ModelT]: One instance per data row, in sheet order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
SheetNotFoundError
|
If the workbook has no such tab. |
SpreadsheetRowError
|
On the first row that fails validation. |
FileNotFoundError
|
If a path does not exist. |
read_xlsx_sheets_async
async
¶
read_xlsx_sheets_async(
source: XlsxSource,
*,
max_rows: int | None = DEFAULT_XLSX_MAX_ROWS,
max_uncompressed_bytes: int | None = DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES,
max_compression_ratio: float | None = DEFAULT_XLSX_MAX_COMPRESSION_RATIO,
semaphore: Semaphore | None = None,
) -> dict[str, list[dict[str, XlsxCellValue]]]
Read every tab of an .xlsx workbook without blocking the event loop.
:func:read_xlsx_sheets in a worker thread, behind the same semaphore
as :func:read_xlsx_async.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
XlsxSource
|
The workbook as bytes, a path, or a binary file object. A file object is read from the worker thread. |
required |
max_rows
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_ROWS
|
max_uncompressed_bytes
|
int | None
|
As in :func: |
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
|
max_compression_ratio
|
float | None
|
As in :func: |
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
|
semaphore
|
Semaphore | None
|
Bounds how many reads run at
once. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[dict[str, XlsxCellValue]]]
|
dict[str, list[dict[str, XlsxCellValue]]]: The rows of each tab, in |
dict[str, list[dict[str, XlsxCellValue]]]
|
tab order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
If a limit is zero or negative. |
SpreadsheetTooLargeError
|
If the workbook passes a limit. |
InvalidSpreadsheetError
|
If the source is not an |
FileNotFoundError
|
If a path does not exist. |
XlsxCellValue
module-attribute
¶
What a cell of a read .xlsx holds.
The type openpyxl (data_only=True) hands back, unchanged:
- a number is
intorfloat— whichever the file wrote. The Google export writes30.0and50in the same column, so declare the fieldfloatorDecimal, notint. Currency is a plain number (84.39); a percentage is the ratio (0.4for40%). - a date is a
datetime— also for a date-only cell, at midnight; a time-only cell is atime, a duration format atimedelta. - a formula is its cached result; a formula whose result is the empty
string reads as
None, like an empty cell. - an error cell (
#DIV/0!) is its text.
XlsxSource
module-attribute
¶
Where a workbook is read from.
bytes (an upload read into memory, an HTTP body), a filesystem path,
or a binary file object — UploadFile.file included.
InvalidSpreadsheetError
¶
InvalidSpreadsheetError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: AppException
The source is not an .xlsx workbook.
Raised for anything openpyxl cannot open as one: a CSV or an old
binary .xls renamed to .xlsx, an empty upload, a ZIP that is
not an Office document. details["reason"] carries the engine's
message for whoever debugs it.
The status is 422: in the common case — a user uploading a file
to an endpoint — the input is what is wrong.
SheetNotFoundError
¶
SheetNotFoundError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: AppException
The workbook has no tab with the requested name or index.
details["sheet"] is what was asked for and details["available"]
lists the tab names the workbook does have, in tab order. Note that a
tab name keeps its whitespace: a tab shown as Setembro may be
called "Setembro ".
SpreadsheetRowError
¶
SpreadsheetRowError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: AppException
One row of a workbook tab did not validate against the target model.
The same contract as
:class:~tempest_fastapi_sdk.spreadsheet.google.GoogleSheetRowError
(which is a subclass, so except SpreadsheetRowError covers both
readers): details["row"] is the row number the spreadsheet shows —
header = 1 — and details["errors"] is Pydantic's error list without
the url and ctx keys. details["sheet"] names the tab.
SpreadsheetTooLargeError
¶
SpreadsheetTooLargeError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: FileTooLargeException
The workbook is past one of the limits the readers enforce.
Raised before the work the limit protects: the decompressed size and
the compression ratio are read from the ZIP's central directory before
openpyxl opens the file, the row limit trips on the first row past
it, and the download limit stops the transfer as soon as the body
passes it. Nothing is truncated: a sheet over a limit is refused, never
read in part.
details["limit"] names the limit — "uncompressed_bytes",
"compression_ratio", "rows" or "download_bytes" —,
details["max"] its value, and details["actual"] what was found
(for "rows" and "download_bytes", the count at which reading
stopped). details["member"] names the ZIP member for the ratio and
details["sheet"] the tab for the row limit (None for a CSV export,
which carries no tab name).
A subclass of :class:~tempest_fastapi_sdk.exceptions.FileTooLargeException,
so the status is 413 like the SDK's upload limit, and
except FileTooLargeException covers both.
DEFAULT_XLSX_MAX_ROWS
module-attribute
¶
Data rows a tab may hold before the readers refuse it.
Counted per tab, blank rows excluded, while the tab is streamed: row
max_rows + 1 raises before it is kept, so the refused part of the sheet
is never held in memory.
The CSV readers of :mod:~tempest_fastapi_sdk.spreadsheet.google
(read_google_sheet, read_google_sheet_as) apply the same default,
counted the same way while the CSV is parsed.
The arithmetic, measured with openpyxl 3.1.5 on CPython 3.11 (one run
per size): a generated tab of 8 columns (id, two texts, three numbers, a
date, a status) read by :func:read_xlsx peaked at 291.5 MB of RSS with
200 000 rows and at 959.1 MB with 1 000 000 rows — about 834 bytes per
row — and took 15.6 s and 78.1 s, about 78 µs per row, on top of the
~125 MB the interpreter and the engine already hold. With this default the
200 000-row tab was refused at row 100 001 after 10.8 s, peaking at 214 MB.
The real workbook measured (a public Google Sheet, 16 tabs, 2 580 rows in
all) is 39 times below it.
DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES
module-attribute
¶
Bytes the workbook's parts may add up to once decompressed (100 MiB).
An .xlsx is a ZIP, so the size of the upload says nothing about the
size the engine parses: a 1.7 MB file measured here inflates to 505 MB of
sheet XML and peaked at 2 278 MB of RSS in the unguarded reader. The sum is
taken from the ZIP's central directory before openpyxl opens anything.
The arithmetic: the same 8-column tab costs ~404 bytes of sheet XML per row
and ~834 bytes of RSS per row once read, so memory grows by about 2 bytes
per byte of XML: a workbook right under 100 MiB holds about 215 MB of
rows (estimated from that ratio, not measured). A tab of the default
:data:DEFAULT_XLSX_MAX_ROWS rows in that shape is ~40 MB of XML, so for
narrow sheets the row limit trips first; this one binds wide sheets, many
tabs and large shared-string tables. The 16-tab Google Sheet measured is
6.1 MB decompressed.
It also bounds time. Without a <dimension> tag — the Google export
writes none — openpyxl scans the whole sheet XML when it opens the
workbook, before the first row is read (a 505 MB sheet took 45.8 s). A file
built to sit just under this limit, with the ratio check off, was refused
at row 100 001 after 11.4 s, peaking at 248 MB: the worst case the defaults
allow, as measured.
The central directory can lie, and zipfile is what keeps the lie
harmless: it stops decompressing a member at the size the directory
declares and checks the CRC there (measured on CPython 3.11 to 3.14). A member
that claims 4 KiB and holds 50 MB reads as 4 KiB and then fails — the CRC
does not match, or the XML is cut short — and either way surfaces as
:class:InvalidSpreadsheetError, never as 50 MB in memory.
DEFAULT_XLSX_MAX_COMPRESSION_RATIO
module-attribute
¶
Decompressed-to-compressed size a single ZIP member may reach.
Checked on members of at least 1 MiB decompressed — a small member cannot
hurt, and its ratio says little. Measured on legitimate workbooks: the
sheets of the 16-tab Google Sheet compress 7.8 to 8.1 times (its worst member,
styles.xml, 11.6), openpyxl output with distinct rows 7.2, and a
tab of 200 000 identical rows — the most repetitive legitimate content —
14.7. A sheet XML built to inflate compressed 294.5 times, and deflate
reaches about 1 032 at most. 100 leaves the legitimate files more than six
times of headroom and refuses the bomb even when its total stays under
:data:DEFAULT_XLSX_MAX_UNCOMPRESSED_BYTES.
DEFAULT_MAX_CONCURRENT_XLSX_READS
module-attribute
¶
Reads the async readers let run at once in one event loop.
openpyxl parses in pure Python and holds the GIL, so the worker
threads behind the *_async readers keep the loop answering but do not
add throughput: concurrent reads share one core. What the limit bounds is
memory — each read holds its whole tab, which is ~834 bytes per row by the
measurement behind :data:DEFAULT_XLSX_MAX_ROWS — and the default thread
pool, which the rest of the service shares. Pass your own
:class:asyncio.Semaphore as semaphore to size it differently.