assets
Assets handling utilities for PlantDB
Provides a collection of helper functions and custom exceptions used by the PlantDB server to validate, create, and extract ZIP archives that store scan datasets. These utilities ensure that uploads conform to the required directory layout, manage atomic file writes, and protect against unsafe extractions such as path-traversal attacks.
Key FeaturesLink
- Header validation for streamed uploads, guaranteeing required metadata.
- Atomic file writing for raw data and streamed chunks.
- Robust ZIP validation that checks required directories, files, and depth.
- Safe archive creation that excludes temporary caches and returns a temporary ZIP path.
- Secure extraction with top-level directory stripping, UTF-8 filename handling, path-traversal protection, and SHA-256 hash verification.
Usage ExamplesLink
>>> from pathlib import Path
>>> import logging
>>> from plantdb.server.services.assets import (
... validate_upload_headers,
... create_zip_for_scan,
... extract_zip_to_scan,
... )
>>> logger = logging.getLogger(__name__)
# Validate request headers (normally ``request.headers`` from Flask)
>>> headers = {
... "Content-Disposition": "attachment; filename=data.zip",
... "Content-Length": "1024",
... "X-File-Path": "scan1/data.zip",
... "X-Chunk-Size": "256",
... }
>>> info = validate_upload_headers(headers)
>>> info
{'rel_filename': 'scan1/data.zip', 'content_length': 1024, 'chunk_size': 256}
# Create a ZIP archive for a scan directory
>>> scan_dir = Path("/data/plantdb/scans/scan1")
>>> zip_path = create_zip_for_scan(scan_dir, logger)
# Extract a validated ZIP archive into a destination directory
>>> dest = Path("/data/plantdb/scans/scan1_extracted")
>>> extracted_files = extract_zip_to_scan(zip_path, dest, logger)
>>> len(extracted_files) > 0
True
ArchiveError
Link
Bases: RuntimeError
Base class for archive-related errors.
ExtractionError
Link
Bases: ArchiveError
Raised when an error occurs while extracting an archive.
FileUploadError
Link
Bases: RuntimeError
Raised when something goes wrong while persisting an uploaded file.
-
Reference API
server
server
services
assets
validate_upload_headers
ValidationError
Link
Bases: ArchiveError
Raised when an uploaded archive fails validation.
create_zip_for_scan
Link
Create a temporary ZIP file containing all files under scan_path (except any webcache directories).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Path
|
The root directory of the scan to archive. |
required |
|
Logger
|
Logger used for diagnostic messages. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path to the created temporary ZIP file. |
Raises:
| Type | Description |
|---|---|
ArchiveError
|
If the ZIP file cannot be created. |
Source code in plantdb/server/services/assets.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
extract_zip_to_scan
Link
extract_zip_to_scan(zip_path, destination, logger)
Extract zip_path into destination while performing safety checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Path
|
Path to the validated temporary ZIP file. |
required |
|
Path
|
Directory where the archive contents should be placed. |
required |
|
Logger
|
Logger for diagnostic output. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of extracted absolute file paths. |
Raises:
| Type | Description |
|---|---|
ExtractionError
|
If any step of the extraction fails. |
Notes
Safety checks include: path traversal, duplicate files, and hash verification
Source code in plantdb/server/services/assets.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
get_scan_path
Link
Resolve the absolute path of a scan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
Database object exposing |
required |
|
str
|
Identifier of the scan. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Absolute directory of the scan. |
Source code in plantdb/server/services/assets.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
is_valid_archive
Link
is_valid_archive(archive_path)
Validate if a given archive meets specific directory and file requirements.
This function checks if the provided archive contains certain required directories and files, and verifies that the directory structure does not exceed a specified depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str or Path
|
The path to the archive file (zip) to be validated. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Returns |
Notes
- The function currently assumes that the required directories and files are all at or above a specified depth in the archive.
- Make sure that the provided
archive_pathpoints to a valid zip file.
See Also
zipfile.ZipFile : Python's built-in module for reading and writing ZIP files.
Examples:
>>> import os
>>> from zipfile import ZipFile
>>> from plantdb.server.services.assets import is_valid_archive
>>> # Creating a valid archive for demonstration purposes
>>> with ZipFile('test_archive.zip', 'w') as zip_ref:
... zip_ref.writestr('images/', '')
... zip_ref.writestr('images/test1.jpg', '')
... zip_ref.writestr('metadata/', '')
... zip_ref.writestr('metadata/data.json', '')
... zip_ref.writestr('files.json', '')
>>> # Validate the archive
>>> is_valid_archive('test_archive.zip')
True
>>> is_valid_archive('/tmp/real_plant.zip')
True
>>> is_valid_archive('/tmp/real_plant_analyzed.zip')
True
Source code in plantdb/server/services/assets.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |
validate_upload_headers
Link
validate_upload_headers(headers)
Verify that the request contains all mandatory headers and return a dictionary with normalized values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
dict
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
FileUploadError
|
If a required header is missing or malformed. |
Source code in plantdb/server/services/assets.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
write_file
Link
write_file(file_path, data)
Write data to file_path in a single operation.
Returns:
| Type | Description |
|---|---|
int
|
Number of bytes written. |
Source code in plantdb/server/services/assets.py
208 209 210 211 212 213 214 215 216 217 218 | |
write_streamed_file
Link
write_streamed_file(file_path, content_length, chunk_size)
Persist a streamed upload. The Flask request object is accessed
globally - this function only deals with the low-level I/O.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Path
|
Destination file. |
required |
|
int
|
Expected total size (from the |
required |
|
int
|
Size of each chunk read from |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of bytes actually written. |
Source code in plantdb/server/services/assets.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |