rest_api
plantdb.server.rest_api Link
This module regroup the classes and methods used to serve a REST API using fsdb_rest_api
CLI.
Archive Link
Archive(db, logger)
Bases: Resource
A RESTful resource class for managing dataset archives.
This class provides functionality to serve and upload dataset archives through HTTP GET and POST methods. It handles ZIP file creation, validation, and extraction while maintaining security and proper cleanup of temporary files.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database instance for accessing and managing scan data. |
logger |
Logger
|
A logger instance for recording operations and errors. |
Initialize the Archive resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance for accessing and managing scan data. |
required |
logger
|
Logger
|
A logger instance for recording operations and errors. |
required |
Source code in plantdb/server/rest_api.py
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 |
|
get Link
get(scan_id)
Create and serve a ZIP archive for the specified scan dataset.
This method creates a temporary ZIP archive containing all files from the specified scan directory (excluding 'webcache' directories) and serves it as a downloadable file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Unique identifier for the scan dataset to be archived. |
required |
Returns:
Type | Description |
---|---|
Response or tuple
|
If successful, returns a Flask response object with the ZIP file for download.
If unsuccessful, returns a tuple (dict, int) containing an error message and
HTTP status code |
Notes
- The scan_id is sanitized before processing
- 'webcache' directories are automatically excluded from the archive
- Temporary files are created with 'fsdb_rest_api_' prefix
- Clean-up is handled automatically after the request
Examples:
>>> # In a terminal, start a (test) REST API with `fsdb_rest_api --test`, then:
>>> import requests
>>> import tempfile
>>> from io import BytesIO
>>> from pathlib import Path
>>> from zipfile import ZipFile
>>> # Get the archive for the 'real_plant_analyzed' dataset with:
>>> zip_file = requests.get("http://127.0.0.1:5000/archive/real_plant_analyzed", stream=True)
>>> # - Extract the archive:
>>> # Read the zip file data into a BytesIO object
>>> zip_data = BytesIO(zip_file.content)
>>> # Create a temporary path to extract the archived data:
>>> tmp_dir = Path(tempfile.mkdtemp())
>>> # Open the zip file and extract non-existing files:
>>> extracted_files = []
>>> with ZipFile(zip_data, 'r') as zip_obj:
>>> for file in zip_obj.namelist():
>>> file_path = tmp_dir / file
>>> zip_obj.extract(file, path=tmp_dir)
>>> extracted_files.append(file)
>>> # Print the list of extracted files:
>>> extracted_files
Source code in plantdb/server/rest_api.py
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 |
|
post Link
post(scan_id)
Handle ZIP file upload and extraction for a scan dataset.
This method processes an uploaded ZIP file, validates its contents and structure, and extracts it to the appropriate location in the database. It includes various security checks and ensures safe extraction of files.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Unique identifier for the scan dataset where the ZIP contents will be extracted. |
required |
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing (dict, int) where the dict contains either:
- On success: {'success': message, 'files': list_of_extracted_files}
- On failure: {'error': error_message}
The integer represents the HTTP status code ( |
Notes
- Performs the following validations:
- Checks for ZIP file presence
- Validates MIME type (must be 'application/zip')
- Verifies file extension (.zip)
- Tests ZIP file integrity
- Validates filename encodings
- Prevents path traversal attacks
- Only extracts files that don't already exist
- Automatically cleans up temporary files
Examples:
>>> # Using requests to upload a ZIP file:
>>> import requests
>>> files = {'zip_file': open('dataset.zip', 'rb')}
>>> response = requests.post("http://127.0.0.1:5000/archive/my_scan", files=files)
>>> print(response.json())
Source code in plantdb/server/rest_api.py
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 |
|
CurveSkeleton Link
CurveSkeleton(db)
Bases: Resource
A RESTful resource that provides access to curve skeleton data for plant scans.
This class implements a REST API endpoint that serves curve skeleton data stored in JSON format. It handles GET requests to retrieve skeleton data for a specific scan ID.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance containing plant scan data and associated filesets. |
Initialize the CurveSkeleton resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database instance providing access to plant scan data. |
required |
Source code in plantdb/server/rest_api.py
1978 1979 1980 1981 1982 1983 1984 1985 1986 |
|
get Link
get(scan_id)
Retrieve the curve skeleton data for a specific scan.
This method handles GET requests to fetch curve skeleton data. It performs validation of the scan ID, retrieves the appropriate fileset, and returns the skeleton data in JSON format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the plant scan to retrieve skeleton data for. Must contain only alphanumeric characters, underscores, dashes, or periods. |
required |
Returns:
Type | Description |
---|---|
Union[dict, Tuple[dict, int]]
|
On success: Dictionary containing the curve skeleton data On failure: Tuple of (error_dict, http_status_code) |
Raises:
Type | Description |
---|---|
ScanNotFoundError
|
If the requested scan ID doesn't exist in the database |
FilesetNotFoundError
|
If the CurveSkeleton fileset is not found for the scan |
FileNotFoundError
|
If the CurveSkeleton file is missing from the fileset |
Notes
- The scan_id is sanitized before processing to ensure security
- Returns HTTP 400 status code for all error conditions with appropriate error messages
- The skeleton data is expected to be in JSON format in the database
Examples:
>>> # Start the REST API server
>>> # Then in a Python console:
>>> import requests
>>> import json
>>>
>>> # Fetch skeleton data for a valid scan
>>> response = requests.get("http://127.0.0.1:5000/skeleton/Col-0_E1_1")
>>> skeleton_data = json.loads(response.content)
>>> print(list(skeleton_data.keys()))
['angles', 'internodes', 'metadata']
>>>
>>> # Example with invalid scan ID
>>> response = requests.get("http://127.0.0.1:5000/skeleton/invalid_id")
>>> print(response.status_code)
400
>>> print(json.loads(response.content))
{'error': "Scan 'invalid_id' not found!"}
Source code in plantdb/server/rest_api.py
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 |
|
DatasetFile Link
DatasetFile(db)
Bases: Resource
A RESTful resource handler for file upload operations in a plant database system.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance that provides access to scan data and file locations. Used for validating scan IDs and determining file storage paths. |
Notes
File operations are performed with proper error handling and cleanup of partial uploads in case of failures.
See Also
plantdb.server.rest_api.ScansList : Resource for managing scan listings plantdb.server.rest_api.File : Resource for file retrieval operations
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance providing access to file locations. |
required |
Source code in plantdb/server/rest_api.py
1330 1331 1332 1333 1334 1335 1336 1337 1338 |
|
post Link
post(scan_id)
Handle POST request to upload and save a file to the server.
This endpoint processes file uploads and saves them to the specified location. It supports both full file uploads and chunked uploads based on the provided headers. The method ensures data integrity by validating the received file size against the Content-Length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Unique identifier for the scan associated with the file upload. Used to determine the base storage path for the file. |
required |
Returns:
Type | Description |
---|---|
Response
|
JSON response with status code and message: - 201: Successful upload with message confirming file save - 400: Bad request (missing headers or invalid parameters) - 500: Server error during file processing |
Notes
Required HTTP headers: - 'Content-Disposition': Contains file information - 'Content-Length': Size of file in bytes - 'X-File-Path': Relative path where file should be saved - 'X-Chunk-Size' (optional): Size of chunks for streamed upload
The method will automatically create any necessary directories in the path. Partial uploads are automatically cleaned up if they fail.
Raises:
Type | Description |
---|---|
Exception
|
When database access fails or file operations encounter errors. All exceptions are caught and returned as HTTP 400 or 500 responses. |
See Also
plantdb.commons.io.write_stream : Helper function for chunked file uploads plantdb.commons.io.write_data : Helper function for complete file uploads
Examples:
>>> # Start the REST API server (in test mode)
>>> # fsdb_rest_api --test
>>> # Request a TOML configuration file
>>> import requests
>>> import toml
>>> # Example POST request with required headers
>>> headers = {
... 'Content-Disposition': 'attachment; filename=data.txt',
... 'Content-Length': '1024',
... 'X-File-Path': 'path/to/data.txt'
... }
>>> response = requests.post(
... 'http://api/scans/scan123/files',
... headers=headers,
... data=file_content
... )
>>> response.status_code
201
>>> response.json()
{'message': 'File path/to/data.txt received and saved'}
Source code in plantdb/server/rest_api.py
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 |
|
File Link
File(db)
Bases: Resource
A RESTful resource class for serving files via HTTP GET requests.
This class implements a REST API endpoint that serves files from a specified database location.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database instance containing the file path configuration. |
Notes
The class requires proper initialization with A database instance that provides a valid path() method for file location resolution.
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance providing access to file locations. |
required |
Source code in plantdb/server/rest_api.py
1249 1250 1251 1252 1253 1254 1255 1256 1257 |
|
get Link
get(path)
Serve a file from the database directory via HTTP.
This method handles GET requests by serving the requested file from
the configured database directory. It uses Flask's send_from_directory
to safely serve the file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
Relative path to the requested file within the database directory. This path will be resolved against the database root path. |
required |
Returns:
Type | Description |
---|---|
Response
|
A Flask response object containing the requested file or an appropriate error response if the file is not found. |
Raises:
Type | Description |
---|---|
NotFound
|
If the requested file does not exist |
Forbidden
|
If the file access is forbidden |
Notes
The file serving is handled securely through Flask's send_from_directory
,
which prevents directory traversal attacks and handles file access permissions.
Examples:
>>> # Start the REST API server (in test mode)
>>> # fsdb_rest_api --test
>>> # Request a TOML configuration file
>>> import requests
>>> import toml
>>> res = requests.get("http://127.0.0.1:5000/files/real_plant_analyzed/pipeline.toml")
>>> cfg = toml.loads(res.content.decode())
>>> print(cfg['Undistorted'])
{'upstream_task': 'ImagesFilesetExists'}
>>> # Request a JSON file
>>> import json
>>> res = requests.get("http://127.0.0.1:5000/files/Col-0_E1_1/files.json")
>>> json.loads(res.content.decode())
Source code in plantdb/server/rest_api.py
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
|
FileCreate Link
FileCreate(db, logger)
Bases: Resource
Represents a File resource creation endpoint in the application.
This class provides the functionality to create new files in filesets.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
The database instance used to create files. |
logger |
Logger
|
The logger instance for recording operations. |
Source code in plantdb/server/rest_api.py
3135 3136 3137 |
|
post Link
post()
Create a new file in a fileset and write data to it.
This method handles POST requests to create a new file with data. It expects multipart/form-data with the file data and JSON metadata.
Notes
The method expects the following form fields: - file: The actual file data - name: str # Required: Name of the file - ext: str # Required: File extension (must be one of VALID_FILE_EXT) - scan_id: str # Required: ID of the scan - fileset_name: str # Required: Name of the fileset - metadata: dict # Optional: Additional metadata for the file (as JSON string)
Returns:
Type | Description |
---|---|
dict
|
Response containing success message or error description |
int
|
HTTP status code (201, 400, 404, or 500) |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> from tempfile import NamedTemporaryFile
>>> from plantdb.client.rest_api import base_url
>>> # Create a YAML temporary file:
>>> with NamedTemporaryFile(suffix='.yaml', mode="w", delete=False) as f: f.write('name: my_file')
>>> file_path = f.name
>>> # Create a new file with metadata in the database:
>>> url = f"{base_url()}/api/file"
>>> # Open the file separately for sending
>>> with open(file_path, 'rb') as file_handle:
... files = {
... 'file': ('test_file.yaml', file_handle, 'application/octet-stream')
... }
... metadata = json.dumps({'description': 'Test document', 'author': 'John Doe'})
... data = {
... 'name': 'new_file',
... 'ext': 'yaml',
... 'scan_id': 'real_plant',
... 'fileset_name': 'images',
... 'metadata': metadata
... }
... response = requests.post(url, files=files, data=data)
>>> print(response.status_code)
201
>>> print(response.json())
{'message': "File 'test_file.yaml' created and written successfully in fileset 'images'."}
>>> file_path.unlink() # Delete the YAML test file
Source code in plantdb/server/rest_api.py
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 |
|
FileMetadata Link
FileMetadata(db, logger)
Bases: Resource
REST API resource for managing file metadata operations.
This class provides endpoints for retrieving and updating metadata associated with files within a scan's fileset.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance for accessing file storage. |
logger |
Logger
|
The logger instance for this resource. |
Notes
All file and fileset names are sanitized before processing to ensure valid formats.
Source code in plantdb/server/rest_api.py
3275 3276 3277 |
|
get Link
get(scan_id, fileset_name, file_name)
Retrieve metadata for a specified file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan containing the fileset. |
required |
fileset_name
|
str
|
The name of the fileset containing the file. |
required |
file_name
|
str
|
The name of the file. |
required |
key
|
str
|
If provided, returns only the value for this specific metadata key. |
required |
Returns:
Type | Description |
---|---|
Union[dict, Any]
|
If key is None, returns the complete metadata dictionary. If key is provided, returns the value for that key. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Get all metadata:
>>> url = f"{base_url()}/api/file/test_plant/images/image_001/metadata"
>>> response = requests.get(url)
>>> print(response.json())
{'metadata': {'description': 'Test file'}}
>>> # Get specific metadata key:
>>> response = requests.get(url+"?key=description")
>>> print(response.json())
{'metadata': 'Test file'}
Source code in plantdb/server/rest_api.py
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 |
|
post Link
post(scan_id, fileset_name, file_name)
Update metadata for a specified file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan containing the fileset. |
required |
fileset_name
|
str
|
The name of the fileset containing the file. |
required |
file_name
|
str
|
The name of the file. |
required |
Returns:
Type | Description |
---|---|
dict
|
Response dictionary with either: * {'metadata': dict} containing updated metadata for successful requests * {'message': str} for error cases |
int
|
HTTP status code (200, 400, 404, or 500). |
Notes
The request body should be a JSON object containing:
- 'metadata' (dict): Required. The metadata to update/set
- 'replace' (bool): Optional. If True
, replaces entire metadata.
If False
(default), updates only specified keys.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> url = f"{base_url()}/api/file/test_plant/images/image_001/metadata"
>>> data = {"metadata": {"description": "Updated description"}}
>>> response = requests.post(url, json=data)
>>> print(response.json())
{'metadata': {'description': 'Updated description'}}
Source code in plantdb/server/rest_api.py
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 |
|
FilesetCreate Link
FilesetCreate(db, logger)
Bases: Resource
Represents a Fileset resource in the application.
This class provides the functionality to create and manage filesets associated with scans.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A dDatabase instance for accessing scan and create fileset. |
logger |
Logger
|
A logger instance for recording operations. |
Source code in plantdb/server/rest_api.py
2783 2784 2785 |
|
post Link
post()
Create a new fileset associated with a scan.
This method handles POST requests to create a new fileset. It validates the input data, ensures required fields are present, creates the fileset with the specified name, and associates it with the given scan ID. Optional metadata can be attached to the fileset.
Notes
The method expects a JSON request body with the following structure: { 'name': str, # Required: Name of the fileset 'scan_id': str, # Required: ID of the associated scan 'metadata': dict # Optional: Additional metadata for the fileset }
Raises:
Type | Description |
---|---|
Exception
|
Any unexpected errors during fileset creation are caught and returned as 500 error responses. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new fileset with metadata:
>>> metadata = {'description': 'This is a test fileset'}
>>> url = f"{base_url()}/api/fileset"
>>> response = requests.post(url, json={'name': 'my_fileset', 'scan_id': 'real_plant', 'metadata': metadata})
>>> print(response.status_code)
201
>>> print(response.json())
{'message': "Fileset 'my_fileset' created successfully in 'real_plant'."}
Source code in plantdb/server/rest_api.py
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 |
|
FilesetFiles Link
FilesetFiles(db, logger)
Bases: Resource
Resource for handling fileset files operations.
Source code in plantdb/server/rest_api.py
3057 3058 3059 |
|
get Link
get(scan_id, fileset_name)
List all files in a specified fileset.
This method retrieves the list of files contained in a fileset using the
list_files()
method from plantdb.commons.fsdb.Fileset
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan containing the fileset. |
required |
fileset_name
|
str
|
The name of the fileset. |
required |
Returns:
Type | Description |
---|---|
dict
|
Response containing either: - On success (200): {'files': list of file information} - On error (404, 500): {'message': error description} |
int
|
HTTP status code (200, 404, or 500) |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # List files in a fileset:
>>> url = f"{base_url()}/api/fileset/real_plant/images/files"
>>> response = requests.get(url)
>>> print(response.status_code)
200
>>> print(response.json())
{'files': ['00000_rgb', '00001_rgb', '00002_rgb', '00003_rgb', '00004_rgb', '00005_rgb', '00006_rgb', '00007_rgb', '00008_rgb', '00009_rgb', '00010_rgb', '00011_rgb', '00012_rgb', '00013_rgb', '00014_rgb', '00015_rgb', '00016_rgb', '00017_rgb', '00018_rgb', '00019_rgb', '00020_rgb', '00021_rgb', '00022_rgb', '00023_rgb', '00024_rgb', '00025_rgb', '00026_rgb', '00027_rgb', '00028_rgb', '00029_rgb', '00030_rgb', '00031_rgb', '00032_rgb', '00033_rgb', '00034_rgb', '00035_rgb', '00036_rgb', '00037_rgb', '00038_rgb', '00039_rgb', '00040_rgb', '00041_rgb', '00042_rgb', '00043_rgb', '00044_rgb', '00045_rgb', '00046_rgb', '00047_rgb', '00048_rgb', '00049_rgb', '00050_rgb', '00051_rgb', '00052_rgb', '00053_rgb', '00054_rgb', '00055_rgb', '00056_rgb', '00057_rgb', '00058_rgb', '00059_rgb']}
Source code in plantdb/server/rest_api.py
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 |
|
FilesetMetadata Link
FilesetMetadata(db, logger)
Bases: Resource
A REST resource for managing fileset metadata operations.
This class provides HTTP endpoints for retrieving and updating metadata associated with filesets within a scan. It supports both complete metadata retrieval and specific key lookups, as well as partial and full metadata updates.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database instance for accessing scan and fileset metadata. |
logger |
Logger
|
A logger instance for error tracking and debugging. |
Notes
All fileset names are sanitized before processing to ensure they contain only alphanumeric characters, underscores, dashes, or periods.
Source code in plantdb/server/rest_api.py
2880 2881 2882 |
|
get Link
get(scan_id, fileset_name)
Retrieve metadata for a specified fileset.
This method retrieves the metadata dictionary for a fileset. Optionally, it can return the value for a specific metadata key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan containing the fileset. |
required |
fileset_name
|
str
|
The name of the fileset. |
required |
key
|
str
|
If provided, returns only the value for this specific metadata key. |
required |
Returns:
Type | Description |
---|---|
Union[dict, Any]
|
If key is None, returns the complete metadata dictionary. If key is provided, returns the value for that key. |
Raises:
Type | Description |
---|---|
FilesetNotFoundError
|
If the specified fileset doesn't exist. |
KeyError
|
If the specified key doesn't exist in the metadata. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new fileset with metadata:
>>> metadata = {'description': 'This is a test fileset'}
>>> url = f"{base_url()}/api/fileset"
>>> response = requests.post(url, json={'name': 'my_fileset', 'scan_id': 'real_plant', 'metadata': metadata})
>>> # Get all metadata:
>>> url = f"{base_url()}/api/fileset/real_plant/my_fileset/metadata"
>>> response = requests.get(url)
>>> print(response.json())
{'metadata': {'description': 'This is a test fileset'}}
>>> # Get specific metadata key:
>>> response = requests.get(url+"?key=description")
>>> print(response.json())
{'metadata': 'This is a test fileset'}
Source code in plantdb/server/rest_api.py
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 |
|
post Link
post(scan_id, fileset_name)
Update metadata for a specified fileset.
This method handles updating metadata for a fileset within a scan. It supports both full metadata replacement and partial updates of specific key-value pairs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Unique identifier for the scan containing the fileset |
required |
fileset_name
|
str
|
Name of the fileset to update metadata for |
required |
Returns:
Type | Description |
---|---|
dict
|
Response dictionary with either: - 'metadata': Updated metadata dictionary on success - 'message': Error message on failure |
int
|
HTTP status code (200 for success, 4xx/5xx for errors) |
Raises:
Type | Description |
---|---|
Exception
|
Any unexpected errors during metadata update will be caught, logged, and returned as a 500 error response. |
Notes
The request body should be a JSON object containing:
- 'metadata' (dict): Required. The metadata to update/set
- 'replace' (bool): Optional. If True
, replaces entire metadata.
If False
(default), updates only specified keys.
Examples:
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new fileset with metadata:
>>> metadata = {'description': 'This is a test fileset'}
>>> url = f"{base_url()}/api/fileset"
>>> data = {'name': 'my_fileset', 'scan_id': 'real_plant', 'metadata': metadata}
>>> response = requests.post(url, json=data)
>>> # Get the original metadata:
>>> url = f"{base_url()}/api/fileset/{data['scan_id']}/{data['name']}/metadata"
>>> response = requests.get(url)
>>> print(response.json())
{'metadata': {'description': 'This is a test fileset'}}
>>> # Update metadata:
>>> metadata_update = {"metadata": {"description": "Updated fileset description", "author": "John Doe"}, "replace": False}
>>> response = requests.post(url, json=metadata_update)
>>> print(response.json())
{'metadata': {'description': 'Updated fileset description', 'author': 'John Doe'}}
>>> # Replace metadata:
>>> metadata_update = {"metadata": {"description": "Brand new description", "version": "2.0"}, "replace": True}
>>> response = requests.post(url, json=metadata_update)
>>> print(response.json())
Source code in plantdb/server/rest_api.py
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 |
|
Image Link
Image(db)
Bases: Resource
RESTful resource for serving and resizing images on demand.
This class handles HTTP GET requests for images stored in the database, with optional resizing capabilities. It serves both original and thumbnail versions of images based on the request parameters.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance containing the image data. |
Notes
The class sanitizes all input parameters to prevent path traversal attacks and ensure valid file access.
Initialize the Image resource with a database connection.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database instance for accessing stored images. |
required |
Source code in plantdb/server/rest_api.py
1583 1584 1585 1586 1587 1588 1589 1590 1591 |
|
get Link
get(scan_id, fileset_id, file_id)
Retrieve and serve an image from the database.
Handles image retrieval requests, optionally resizing the image based on the 'size' query parameter. Supports both original size and thumbnail versions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the scan containing the image. |
required |
fileset_id
|
str
|
Identifier for the fileset within the scan. |
required |
file_id
|
str
|
Identifier for the specific image file. |
required |
size
|
(orig, large, thumb)
|
If an integer, use it as the size of the cached image to create and return.
Otherwise, should be one of the valid string.
Should be passed as a URL query parameter.
Default to |
'orig'
|
Returns:
Type | Description |
---|---|
Response
|
HTTP response containing the image data with 'image/jpeg' mimetype. |
Notes
- All input parameters are sanitized before use.
- The 'size' parameter defaults to 'thumb' if not specified.
- Supported string size values are:
'thumb'
: image max width and height to150
;'large'
: image max width and height to1500
;'orig'
: original image, no chache;
See Also
plantdb.server.rest_api.sanitize_name : Input sanitization & validation function. plantdb.server.webcache.image_path : Image path resolution function with caching and resizing options.
Examples:
>>> # In a terminal, start a (test) REST API with `fsdb_rest_api --test`, then:
>>> import numpy as np
>>> import requests
>>> from io import BytesIO
>>> from PIL import Image
>>> # Get the first image as a thumbnail (default):
>>> res = requests.get("http://127.0.0.1:5000/image/real_plant_analyzed/images/00000_rgb", stream=True)
>>> img = Image.open(BytesIO(res.content))
>>> np.asarray(img).shape
(113, 150, 3)
>>> # Get the first image in original size:
>>> res = requests.get("http://127.0.0.1:5000/image/real_plant_analyzed/images/00000_rgb", stream=True, params={"size": "orig"})
>>> img = Image.open(BytesIO(res.content))
>>> np.asarray(img).shape
(1080, 1440, 3)
Source code in plantdb/server/rest_api.py
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 |
|
Login Link
Login(db)
Bases: Resource
A RESTful resource to handle user login and authentication processes.
This class processes HTTP requests for user authentication, including checking if a username exists in the database and validating login credentials.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database object that provides access to user-related operations such as checking if a user exists and validating user credentials. |
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database object for accessing user data. |
required |
Source code in plantdb/server/rest_api.py
760 761 762 763 764 765 766 767 768 |
|
check_credentials Link
check_credentials(username, password)
Validates user credentials against the database.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
username
|
str
|
The username provided by the user or client for authentication. |
required |
password
|
str
|
The password corresponding to the username for authentication. |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in plantdb/server/rest_api.py
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 |
|
get Link
get()
Checks if a given username exists in the database and returns the result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
username
|
str
|
The username to check in the database. This must be a non-empty string and served as a query parameter. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary with the result and an HTTP status code.
If the |
int
|
An HTTP status code. If the |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> # Check if user exists (valid username):
>>> response = requests.get("http://127.0.0.1:5000/login?username=anonymous")
>>> print(response.json())
{'username': 'anonymous', 'exists': True}
>>> # Check if user exists (invalid username):
>>> response = requests.get("http://127.0.0.1:5000/login?username=superman")
>>> print(response.json())
{'username': 'superman', 'exists': False}
Source code in plantdb/server/rest_api.py
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 |
|
post Link
post()
Handle user authentication via POST request with username and password.
This method processes a POST request containing user credentials (username and password) and validates them against stored user data. It returns authentication status and a descriptive message.
Returns:
Type | Description |
---|---|
dict
|
A dictionary with the following keys and values:
- 'authenticated' : bool
The result of the authentication process ( |
int
|
The HTTP status code ( |
Raises:
Type | Description |
---|---|
BadRequest
|
If the request doesn't contain valid JSON data (handled by Flask) |
Notes
The method expects a JSON payload with 'username' and 'password' fields.
The authentication process uses the check_credentials
method to validate
the provided credentials against the database.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Valid login request
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'anonymous', 'password': 'AlanMoore'})
>>> print(response.json())
{'authenticated': True, 'message': 'Login successful. Welcome, Guy Fawkes!'}
>>> print(response.status_code)
200
>>> # Invalid request (missing credentials)
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'anonymous'})
>>> print(response.json())
{'authenticated': False, 'message': 'Missing username or password'}
>>> print(response.status_code)
400
Source code in plantdb/server/rest_api.py
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 |
|
Mesh Link
Mesh(db)
Bases: Resource
RESTful resource for serving triangular mesh data via HTTP.
This class implements a REST endpoint that provides access to triangular mesh data stored in a database. It supports GET requests and can optionally handle mesh size parameters.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Reference to the database instance. |
Notes
The mesh data is served in PLY format as an octet-stream.
Initialize the Mesh resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
The database instance containing the mesh data. |
required |
Source code in plantdb/server/rest_api.py
1885 1886 1887 1888 1889 1890 1891 1892 1893 |
|
get Link
get(scan_id, fileset_id, file_id)
Retrieve and serve a triangular mesh file.
This method handles GET requests for mesh data, supporting optional size parameters. It sanitizes input parameters and serves the mesh file from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the scan containing the mesh. |
required |
fileset_id
|
str
|
Identifier for the fileset within the scan. |
required |
file_id
|
str
|
Identifier for the specific mesh file. |
required |
size
|
orig
|
A string value specifying the size of the mesh to return.
Should be passed as a URL query parameter.
Default to |
'orig'
|
Returns:
Type | Description |
---|---|
Response
|
HTTP response containing the mesh data as an octet-stream. |
Raises:
Type | Description |
---|---|
NotFound
|
If the requested mesh file doesn't exist |
Notes
- The 'size' parameter currently only supports 'orig' value
- All identifiers are sanitized before use
- The mesh is served as a binary PLY file
See Also
plantdb.server.rest_api.sanitize_name : Function used to validate input parameters plantdb.server.webcache.mesh_path : Function to retrieve mesh file path
Examples:
>>> # In a terminal, start a (test) REST API with `fsdb_rest_api --test`, then:
>>> import requests
>>> from plyfile import PlyData
>>> from io import BytesIO
>>> # Request a mesh file
>>> url = "http://127.0.0.1:5000/mesh/real_plant_analyzed/TriangleMesh_9_most_connected_t_open3d_00e095c359/TriangleMesh"
>>> response = requests.get(url)
>>> # Parse the PLY data
>>> mesh_data = PlyData.read(BytesIO(response.content))
>>> # Access vertex coordinates
>>> vertices = mesh_data['vertex']
>>> x_coords = list(vertices['x'])
Source code in plantdb/server/rest_api.py
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 |
|
PointCloud Link
PointCloud(db)
Bases: Resource
RESTful resource for serving and optionally downsampling point cloud data.
This class handles HTTP GET requests for point cloud data stored in PLY format, with support for different sampling densities. It can serve both original and preview versions of point clouds, or custom downsampling based on voxel size.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance containing the point cloud data. |
Notes
The class sanitizes all input parameters to prevent path traversal attacks and ensures valid file access. Point clouds are served in PLY format with 'application/octet-stream' mimetype.
Initialize the PointCloud resource with a database connection.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database instance for accessing stored point cloud data. |
required |
Source code in plantdb/server/rest_api.py
1683 1684 1685 1686 1687 1688 1689 1690 1691 |
|
get Link
get(scan_id, fileset_id, file_id)
Retrieve and serve a point cloud from the database.
Handles point cloud retrieval requests with optional downsampling based on the 'size' query parameter. Supports original size, preview, and custom voxel-based downsampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the scan containing the point cloud. |
required |
fileset_id
|
str
|
Identifier for the fileset within the scan. |
required |
file_id
|
str
|
Identifier for the specific point cloud file. |
required |
size
|
(orig, preview)
|
If a float, use it to downsample the pointcloud and return.
Otherwise, should be one of the valid string.
Should be passed as a URL query parameter.
Default to |
'orig'
|
Returns:
Type | Description |
---|---|
Response
|
HTTP response containing the PLY data with 'application/octet-stream' mimetype. |
Notes
- The 'size' parameter can be:
- 'orig': original point cloud
- 'preview': downsampled preview version
- float value: custom voxel size for downsampling
- Defaults to 'preview' if size parameter is invalid
- All input parameters are sanitized before use
See Also
plantdb.server.rest_api.sanitize_name : Input sanitization & validation function. plantdb.server.webcache.pointcloud_path : Point cloud path resolution function with caching and downsampling options.
Examples:
>>> # In a terminal, start a (test) REST API with `fsdb_rest_api --test`, then:
>>> import requests
>>> from plyfile import PlyData
>>> from io import BytesIO
>>> # Get original point cloud:
>>> res = requests.get("http://127.0.0.1:5000/pointcloud/real_plant_analyzed/PointCloud_1_0_1_0_10_0_7ee836e5a9/PointCloud")
>>> pcd_data = PlyData.read(BytesIO(res.content))
>>> # Access point X-coordinates:
>>> list(pcd_data['vertex']['x'])
>>> # Get preview (downsampled) version
>>> res = requests.get("http://127.0.0.1:5000/pointcloud/real_plant_analyzed/PointCloud_1_0_1_0_10_0_7ee836e5a9/PointCloud", params={"size": "preview"})
>>> # Get custom downsampled version (voxel size 0.01)
>>> res = requests.get("http://127.0.0.1:5000/pointcloud/real_plant_analyzed/PointCloud_1_0_1_0_10_0_7ee836e5a9/PointCloud", params={"size": "0.01"})
Source code in plantdb/server/rest_api.py
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 |
|
PointCloudGroundTruth Link
PointCloudGroundTruth(db)
Bases: Resource
A RESTful resource for serving ground-truth point-cloud data.
This class handles HTTP GET requests for point-cloud data, with optional downsampling capabilities based on the requested size parameter.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
The database instance used to retrieve point-cloud data. |
Initialize the PointCloudGroundTruth resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database instance providing access to the point-cloud data. |
required |
Source code in plantdb/server/rest_api.py
1784 1785 1786 1787 1788 1789 1790 1791 1792 |
|
get Link
get(scan_id, fileset_id, file_id)
Retrieve and serve a ground-truth point-cloud file.
Fetches the requested point-cloud data from the cache, potentially downsampling it based on the size parameter provided in the query string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the scan to retrieve. |
required |
fileset_id
|
str
|
Identifier for the fileset within the scan. |
required |
file_id
|
str
|
Identifier for the specific point-cloud file. |
required |
size
|
(orig, preview)
|
If a float, use it to downsample the pointcloud and return.
Otherwise, should be one of the valid string.
Should be passed as a URL query parameter.
Default to |
'orig'
|
Returns:
Type | Description |
---|---|
Response
|
HTTP response containing the point-cloud data as an octet-stream. |
Raises:
Type | Description |
---|---|
NotFound
|
If the requested point-cloud file doesn't exist. |
Notes
- The 'size' parameter can be specified in the query string as:
- 'orig': Original size
- 'preview': Preview size (default)
- A float value: Custom voxel size for downsampling
- All identifiers are sanitized before use
- Invalid size parameters default to 'preview'
- Response mimetype is 'application/octet-stream'
Examples:
>>> # Request original size point-cloud
>>> response = get('/api/scan123/fileset1/cloud1?size=orig')
>>>
>>> # Request preview size
>>> response = get('/api/scan123/fileset1/cloud1?size=preview')
>>>
>>> # Request custom voxel size
>>> response = get('/api/scan123/fileset1/cloud1?size=0.01')
Source code in plantdb/server/rest_api.py
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 |
|
Refresh Link
Refresh(db)
Bases: Resource
RESTful resource for reloading the database on demand.
A concrete implementation of Flask-RESTful Resource that provides an endpoint to force reload the plant database. This is useful when the underlying data has changed and needs to be refreshed in the running application.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
The database instance used for reloading data. |
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance to reload. |
required |
Source code in plantdb/server/rest_api.py
1493 1494 1495 1496 1497 1498 1499 1500 1501 |
|
get Link
get()
Force the plant database to reload.
This endpoint triggers a reload of the plant database data. It can either reload the entire database or selectively reload data for a specific plant scan.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for a specific plant scan to reload. If not provided, reloads the entire database. |
required |
Returns:
Type | Description |
---|---|
Response
|
A Response object with:
- Status code |
Raises:
Type | Description |
---|---|
FilesetNotFoundError
|
If the specified scan_id refers to a non-existent fileset |
ScanNotFoundError
|
If the specified scan_id refers to a non-existent scan |
Exception
|
For any other unexpected errors during reload |
Notes
This endpoint is rate-limited to 1
request per minute to prevent excessive
database reloads.
See Also
plantdb.server.rest_api.rate_limit : Decorator that implements request rate limiting plantsb.fsdb.FSDB.reload : The underlying database reload method
Examples:
>>> # Start the REST API server (in test mode)
>>> # fsdb_rest_api --test
>>> import requests
>>> # Refresh entire database
>>> response = requests.get("http://127.0.0.1:5000/refresh")
>>> response.status_code
200
>>>
>>> # Refresh specific scan
>>> response = requests.get("http://127.0.0.1:5000/refresh?scan_id=real_plant")
>>> response.status_code
200
Source code in plantdb/server/rest_api.py
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 |
|
Register Link
Register(db)
Bases: Resource
A RESTful resource to manage user registration via HTTP POST requests.
Responsible for handling the registration process by validating and creating user records in the database. This class provides a structured way to interact with user data, ensuring error handling and proper responses for client requests.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance used for storing and managing user records. |
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database object for with user records. |
required |
Source code in plantdb/server/rest_api.py
663 664 665 666 667 668 669 670 671 |
|
post Link
post()
Handle HTTP POST request to register a new user.
Processes user registration by validating the input data and creating a new user in the database. Expects a JSON payload in the request body with required user details.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
username
|
str
|
Unique identifier for the user. Should originate from the JSON payload and be a non-empty string. |
required |
fullname
|
str
|
User's full name. Should originate from the JSON payload and be a non-empty string. |
required |
password
|
str
|
User's password for authentication. Should originate from the JSON payload and be a non-empty string. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary with the following keys and values: - 'success' (bool): Indicates if operation was successful - 'message' (str): Description of the operation result |
int
|
HTTP status code ( |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> # Create a new user:
>>> new_user = {"username":"batman", "fullname":"Bruce Wayne", "password":"Alfred"}
>>> response = requests.post("http://127.0.0.1:5000/register", json=new_user)
>>> res_dict = response.json()
>>> res_dict["success"]
True
>>> res_dict["message"]
'User successfully created'
Source code in plantdb/server/rest_api.py
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 |
|
Scan Link
Scan(db, logger)
Bases: Resource
A RESTful resource class for serving scan dataset information.
This class handles HTTP GET requests for scan datasets, providing detailed information about the scan including metadata, file locations, and task status.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
The database instance used to retrieve scan information. |
logger |
Logger
|
The logger instance for recording operations. |
Notes
The class sanitizes scan IDs before processing requests to ensure security. All responses are returned as JSON-serializable dictionaries.
See Also
plantdb.server.rest_api.get_scan_info : Function used to collect and format scan information plantdb.server.rest_api.sanitize_name : Function used to validate and clean scan IDs
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance providing access to scan data. |
required |
logger
|
Logger
|
A logger instance for recording operations and errors. |
required |
Source code in plantdb/server/rest_api.py
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 |
|
get Link
get(scan_id)
Retrieve detailed information about a specific scan dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the scan dataset. Must contain only alphanumeric characters, underscores, dashes, or periods. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing scan information with the following keys: - 'metadata' (dict): Contains scan date, object information, and image count - 'files' (dict): Contains paths to related files and archives - 'tasks' (dict): Contains information about processing task status - 'thumbnail' (str): URI to the scan's thumbnail image |
Raises:
Type | Description |
---|---|
ValueError
|
If the scan_id contains invalid characters |
NotFoundError
|
If the specified scan does not exist in the database |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> # Get detailed information about a specific dataset
>>> response = requests.get("http://127.0.0.1:5000/scans/real_plant_analyzed")
>>> scan_data = json.loads(response.content)
>>> # Access metadata information
>>> print(scan_data['metadata']['date'])
2024-08-19 11:12:25
>>> # Check if point cloud processing is complete
>>> print(scan_data['tasks']['point_cloud'])
True
Source code in plantdb/server/rest_api.py
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 |
|
post Link
post(scan_id)
Create a new scan dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Identifier for the new scan dataset. Must contain only alphanumeric characters, underscores, dashes, or periods. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing the response with following possible structures: - On success: {'message': 'Scan created successfully', 'scan_id': scan_id} - On error: {'error': error_message} |
Notes
HTTP status codes: - 201 : Created successfully - 400 : Bad request (invalid scan_id) - 409 : Conflict (scan already exists) - 500 : Internal server error
Source code in plantdb/server/rest_api.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 |
|
ScanCreate Link
ScanCreate(db, logger)
Bases: Resource
Represents a Scan resource creation endpoint in the application.
This class provides the functionality to create new scans in the database.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database instance used to create scans. |
logger |
Logger
|
A logger instance for recording operations. |
Source code in plantdb/server/rest_api.py
2476 2477 2478 |
|
post Link
post()
Create a new scan in the database.
This method handles POST requests to create a new scan. It validates the input data, ensures required fields are present, and creates the scan with the specified name and optional metadata.
Notes
The method expects a JSON request body with the following structure: { 'name': str, # Required: Name of the scan 'metadata': dict # Optional: Additional metadata for the scan }
Raises:
Type | Description |
---|---|
Exception
|
Any unexpected errors during scan creation are caught and returned as 500 error responses. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new scan with metadata:
>>> metadata = {'description': 'Test plant scan'}
>>> url = f"{base_url()}/api/scan"
>>> response = requests.post(url, json={'name': 'test_plant', 'metadata': metadata})
>>> print(response.status_code)
201
>>> print(response.json())
{'message': "Scan 'test_plant' created successfully."}
Source code in plantdb/server/rest_api.py
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 |
|
ScanFilesets Link
ScanFilesets(db, logger)
Bases: Resource
REST API resource for managing scan filesets operations.
This class provides endpoints to interact with filesets within a scan. It allows listing filesets with optional query filtering and fuzzy matching capabilities.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
A database instance for accessing scan and create fileset. |
logger |
Logger
|
A logger instance for recording operations. |
Source code in plantdb/server/rest_api.py
2714 2715 2716 |
|
get Link
get(scan_id)
List all filesets in a specified scan.
This method retrieves the list of filesets contained in a scan using the
list_filesets()
method from plantdb.commons.fsdb.Scan
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan. |
required |
Returns:
Type | Description |
---|---|
dict
|
Response containing either: - On success (200): {'filesets': list of fileset IDs} - On error (404, 500): {'message': error description} |
int
|
HTTP status code (200, 404, or 500) |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # List filesets in a scan:
>>> url = f"{base_url()}/api/scan/real_plant/filesets"
>>> response = requests.get(url)
>>> print(response.status_code)
200
>>> print(response.json())
{'filesets': ['images']}
Source code in plantdb/server/rest_api.py
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 |
|
ScanMetadata Link
ScanMetadata(db, logger)
Bases: Resource
Resource class for managing scan metadata operations through REST API endpoints.
This class provides HTTP endpoints for retrieving and updating scan metadata through a RESTful interface. It handles both complete metadata operations and individual key access.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database instance for accessing and managing scan data. |
logger |
Logger
|
Logger instance for recording operations and errors. |
Source code in plantdb/server/rest_api.py
2554 2555 2556 |
|
get Link
get(scan_id)
Retrieve metadata for a specified scan.
This method retrieves the metadata dictionary for a scan. Optionally, it can return the value for a specific metadata key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan. |
required |
key
|
str
|
If provided, returns only the value for this specific metadata key. |
required |
Returns:
Type | Description |
---|---|
Union[dict, Any]
|
If key is None, returns the complete metadata dictionary. If key is provided, returns the value for that key. |
Raises:
Type | Description |
---|---|
ScanNotFoundError
|
If the specified scan doesn't exist. |
KeyError
|
If the specified key doesn't exist in the metadata. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new scan with metadata:
>>> metadata = {'description': 'Test plant scan'}
>>> url = f"{base_url()}/api/scan"
>>> response = requests.post(url, json={'name': 'test_plant', 'metadata': metadata})
>>> # Get all metadata:
>>> url = f"{base_url()}/api/scan/test_plant/metadata"
>>> response = requests.get(url)
>>> print(response.json())
{'metadata': {'owner': 'anonymous', 'description': 'Test plant scan'}}
>>> # Get specific metadata key:
>>> response = requests.get(url+"?key=description")
>>> print(response.json())
{'metadata': 'Test plant scan'}
Source code in plantdb/server/rest_api.py
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 |
|
post Link
post(scan_id)
Update metadata for a specified scan.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
The ID of the scan to update metadata for |
required |
Returns:
Type | Description |
---|---|
dict
|
Response dictionary with either: - 'metadata': Updated metadata dictionary on success - 'message': Error message on failure |
int
|
HTTP status code (200 for success, 4xx/5xx for errors) |
Notes
The request body should be a JSON object containing:
- 'metadata' (dict): Required. The metadata to update/set
- 'replace' (bool): Optional. If True
, replaces entire metadata.
If False
(default), updates only specified keys.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> from plantdb.client.rest_api import base_url
>>> # Create a new scan with metadata:
>>> metadata = {'description': 'Test plant scan'}
>>> url = f"{base_url()}/api/scan"
>>> response = requests.post(url, json={'name': 'test_plant', 'metadata': metadata})
>>> # Update scan metadata:
>>> url = f"{base_url()}/api/scan/test_plant/metadata"
>>> data = {"metadata": {"description": "Updated scan description"}}
>>> response = requests.post(url, json=data)
>>> print(response.json())
{'metadata': {'owner': 'anonymous', 'description': 'Updated scan description'}}
Source code in plantdb/server/rest_api.py
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 |
|
ScansList Link
ScansList(db)
Bases: Resource
A RESTful resource for managing and retrieving scan datasets.
This class implements a REST API endpoint that provides access to scan datasets. It supports filtered queries and fuzzy matching capabilities through HTTP GET requests.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database connection object used to interact with the scan datasets. |
See Also
flask_restful.Resource : Base class for RESTful resources
Initialize the ScansList resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
Database connection object for accessing scan data. |
required |
Source code in plantdb/server/rest_api.py
920 921 922 923 924 925 926 927 928 |
|
get Link
get()
Retrieve a list of scan datasets with optional filtering.
This endpoint provides access to scan datasets stored in the database. It allows filtering of results using a JSON-formatted query string and supports fuzzy matching for string-based searches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filterQuery
|
str
|
JSON-formatted string containing filter criteria for querying datasets.
Should be passed as a URL query parameter.
Example: |
required |
fuzzy
|
bool
|
Whether to enable fuzzy matching for string fields in the filter query.
Should be passed as a URL query parameter.
Default is |
required |
Returns:
Type | Description |
---|---|
list
|
The List of scan datasets matching the filter criteria. Each item is a dictionary containing dataset metadata. |
int
|
HTTP status code ( |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Get an info dict about all dataset:
>>> response = requests.get("http://127.0.0.1:5000/scans")
>>> scans_list = response.json()
>>> print(scans_list) # List the known dataset ids
['arabidopsis000', 'virtual_plant_analyzed', 'real_plant_analyzed', 'real_plant', 'virtual_plant']
>>> # Get datasets with fuzzy filtering
>>> filter_query = {"object":{"species":"Arabidopsis.*"}}
>>> response = requests.get("http://127.0.0.1:5000/scans", params={"filterQuery": json.dumps(filter_query), "fuzzy": "true"})
>>> filtered_scans = response.json()
>>> print(filtered_scans) # List the filtered dataset ids
Source code in plantdb/server/rest_api.py
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 |
|
ScansTable Link
ScansTable(db, logger)
Bases: Resource
A RESTful resource for managing and retrieving scan dataset information.
This class provides a REST API endpoint to serve information about scan datasets. It supports filtering datasets based on query parameters and returns detailed information about each matching scan.
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
Database connection object used to interact with the scan datasets. |
logger |
Logger
|
The logger instance for this resource. |
See Also
plantdb.server.rest_api.get_scan_info : Function used to extract information for each scan
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> # Get all scan datasets
>>> response = requests.get("http://127.0.0.1:5000/scans_info")
>>> scans = json.loads(response.content)
>>> print(scans[0]['id']) # print the id of the first scan dataset
>>> print(scans[0]['metadata']) # print the metadata of the first scan dataset
>>> # Get filtered results using query
>>> query = {"object": {"species": "Arabidopsis.*"}}
>>> response = requests.get("http://127.0.0.1:5000/scans_info", params={"filterQuery": json.dumps(query), "fuzzy": "true"})
>>> filtered_scans = json.loads(response.content)
>>> print(filtered_scans[0]['id']) # print the id of the first scan dataset matching the query
Initialize the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance providing access to scan data. |
required |
logger
|
Logger
|
A logger instance for recording operations and errors. |
required |
Source code in plantdb/server/rest_api.py
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 |
|
get Link
get()
Retrieve a list of scan dataset information.
This method handles GET requests to retrieve scan information. It supports filtering through query parameters and returns detailed information about matching scans.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filterQuery
|
str
|
JSON string containing filter criteria for scans. Must be valid JSON that can be parsed into a query dict. |
required |
fuzzy
|
bool
|
If |
required |
Returns:
Type | Description |
---|---|
list of dict
|
List of dictionaries containing scan information with: - 'metadata' (dict): Scan metadata including acquisition date, object info - 'tasks' (dict): Information about processing tasks - 'files' (dict): File paths and URIs related to the scan |
Raises:
Type | Description |
---|---|
JSONDecodeError
|
If the provided filterQuery parameter is not valid JSON. |
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> import json
>>> # Get an info dict about all dataset:
>>> res = requests.get("http://127.0.0.1:5000/scans_info")
>>> scans_list = json.loads(res.content)
>>> # List the known dataset id:
>>> print(scans_list)
['arabidopsis000', 'virtual_plant_analyzed', 'real_plant_analyzed', 'real_plant', 'virtual_plant', 'models']
>>> res = requests.get('http://127.0.0.1:5000/scans_info?filterQuery={"object":{"species":"Arabidopsis.*"}}&fuzzy="true"')
>>> res.content.decode()
Source code in plantdb/server/rest_api.py
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 |
|
Sequence Link
Sequence(db)
Bases: Resource
A RESTful resource class that serves angle and internode sequences data.
This class provides a REST API endpoint to retrieve angle and internode sequence data for plant scans. It handles data retrieval from a database and supports filtering by sequence type (angles, internodes, or fruit_points).
Attributes:
Name | Type | Description |
---|---|---|
db |
FSDB
|
The database instance used for retrieving scan data. |
Initialize the Sequence resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db
|
FSDB
|
A database instance containing plant scan data and related measurements. |
required |
Source code in plantdb/server/rest_api.py
2089 2090 2091 2092 2093 2094 2095 2096 2097 |
|
get Link
get(scan_id)
Retrieve angle and internode sequences data for a given scan.
This method serves as a REST API endpoint to fetch angle, internode, and fruit point sequence data from plant scans. It can return either all sequence data or specific sequence types based on the query parameter 'type'.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan_id
|
str
|
Unique identifier for the plant scan. Must contain only alphanumeric characters, underscores, dashes, or periods. |
required |
Returns:
Type | Description |
---|---|
Union[dict, list, tuple[dict, int]]
|
If successful and type='all' (default): Dictionary containing all sequence data with keys 'angles', 'internodes', and 'fruit_points' If successful and type in ['angles', 'internodes', 'fruit_points']: List of sequence values for the specified type If error: Tuple of (error_dict, HTTP_status_code) |
Raises:
Type | Description |
---|---|
ScanNotFoundError
|
If the specified scan_id does not exist in the database |
FilesetNotFoundError
|
If the AnglesAndInternodes fileset is not found |
FileNotFoundError
|
If the AnglesAndInternodes file is not found within the fileset |
Notes
- The 'type' query parameter accepts 'angles', 'internodes', or 'fruit_points'
- Invalid 'type' parameters will return the complete data dictionary
- All responses are JSON-encoded
- Input scan_id is sanitized before processing
See Also
plantdb.server.rest_api.sanitize_name : Function used to validate and clean scan_id plantdb.server.rest_api.compute_fileset_matches : Function to match filesets with tasks
Examples:
>>> # Get all sequence data
>>> import requests
>>> import json
>>> response = requests.get("http://127.0.0.1:5000/sequence/real_plant_analyzed")
>>> data = json.loads(response.content.decode('utf-8'))
>>> # Expected output: {'angles': [...], 'internodes': [...], 'fruit_points': [...]}
>>> # Get only angles data
>>> response = requests.get(
... "http://127.0.0.1:5000/sequence/real_plant_analyzed",
... params={'type': 'angles'}
... )
>>> angles = json.loads(response.content.decode('utf-8'))
>>> # Expected output: [angle1, angle2, ...]
Source code in plantdb/server/rest_api.py
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 |
|
compute_fileset_matches Link
compute_fileset_matches(scan)
Return a dictionary mapping the scan tasks to fileset names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan
|
The scan instance to list the filesets from. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping the scan tasks to fileset names. |
Examples:
>>> from plantdb.server.rest_api import compute_fileset_matches
>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db(with_fileset=True)
>>> scan = db.get_scan("myscan_001")
>>> compute_fileset_matches(scan)
{'fileset': 'fileset_001'}
>>> db.disconnect() # clean up (delete) the temporary dummy database
Source code in plantdb/server/rest_api.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
get_file_uri Link
get_file_uri(scan, fileset, file)
Return the URI for the corresponding scan/fileset/file
tree.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan or str
|
A |
required |
fileset
|
Fileset or str
|
A |
required |
file
|
File or str
|
A |
required |
Returns:
Type | Description |
---|---|
str
|
The URI for the corresponding |
Examples:
>>> from plantdb.server.rest_api import get_file_uri
>>> from plantdb.commons.test_database import test_database
>>> from plantdb.server.rest_api import compute_fileset_matches
>>> db = test_database('real_plant_analyzed')
>>> db.connect()
>>> scan = db.get_scan('real_plant_analyzed')
>>> fs_match = compute_fileset_matches(scan)
>>> fs = scan.get_fileset(fs_match['PointCloud'])
>>> f = fs.get_file("PointCloud")
>>> get_file_uri(scan, fs, f)
'/files/real_plant_analyzed/PointCloud_1_0_1_0_10_0_7ee836e5a9/PointCloud.ply'
Source code in plantdb/server/rest_api.py
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 |
|
get_image_uri Link
get_image_uri(scan, fileset, file, size='orig')
Return the URI for the corresponding scan/fileset/file
tree.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan or str
|
A |
required |
fileset
|
Fileset or str
|
A |
required |
file
|
File or str
|
A |
required |
size
|
(orig, large, thumb)
|
If an integer, use it as the size of the cached image to create and return.
Otherwise, should be one of the following strings, default to
|
'orig'
|
Returns:
Type | Description |
---|---|
str
|
The URI for the corresponding |
Examples:
>>> from plantdb.server.rest_api import get_image_uri
>>> from plantdb.commons.test_database import test_database
>>> from plantdb.server.rest_api import compute_fileset_matches
>>> db = test_database('real_plant_analyzed')
>>> db.connect()
>>> scan = db.get_scan('real_plant_analyzed')
>>> get_image_uri(scan, 'images', '00000_rgb.jpg', size='orig')
'/image/real_plant_analyzed/images/00000_rgb.jpg?size=orig'
>>> get_image_uri(scan, 'images', '00011_rgb.jpg', size='thumb')
'/image/real_plant_analyzed/images/00011_rgb.jpg?size=thumb'
Source code in plantdb/server/rest_api.py
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 395 396 397 398 399 400 401 402 |
|
get_path Link
get_path(f, db_prefix='/files/')
Return the path to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f
|
File
|
The file to get the path for. |
required |
db_prefix
|
str
|
A prefix to use... ??? |
'/files/'
|
Returns:
Type | Description |
---|---|
str
|
The path to the file. |
Source code in plantdb/server/rest_api.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
|
get_scan_data Link
get_scan_data(scan, **kwargs)
Get the scan information and data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan
|
The scan instance to get the information and data from. |
required |
Other Parameters:
Name | Type | Description |
---|---|---|
logger |
Logger
|
A logger to use with this method, default to a logger created on the fly with a |
Returns:
Type | Description |
---|---|
dict
|
The scan information dictionary. |
Examples:
>>> from plantdb.server.rest_api import get_scan_data
>>> from plantdb.commons.test_database import test_database
>>> db = test_database('real_plant_analyzed')
>>> db.connect()
>>> scan = db.get_scan('real_plant_analyzed')
>>> scan_data = get_scan_data(scan)
>>> print(scan_data['id'])
real_plant_analyzed
>>> print(scan_data['filesUri'])
{'pointCloud': PosixPath('/tmp/ROMI_DB/real_plant_analyzed/PointCloud_1_0_1_0_10_0_7ee836e5a9/PointCloud.ply'), 'mesh': PosixPath('/tmp/ROMI_DB/real_plant_analyzed/TriangleMesh_9_most_connected_t_open3d_00e095c359/TriangleMesh.ply'), 'skeleton': PosixPath('/tmp/ROMI_DB/real_plant_analyzed/CurveSkeleton__TriangleMesh_0393cb5708/CurveSkeleton.json'), 'tree': PosixPath('/tmp/ROMI_DB/real_plant_analyzed/TreeGraph__False_CurveSkeleton_c304a2cc71/TreeGraph.p')}
>>> print(scan_data['camera']["model"])
SIMPLE_RADIAL
>>> db.disconnect()
Source code in plantdb/server/rest_api.py
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 453 454 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 |
|
get_scan_date Link
get_scan_date(scan)
Get the acquisition datetime of a scan.
Try to get the data from the scan metadata 'acquisition_date', else from the directory creation time.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan
|
The scan instance to get the date & time from. |
required |
Returns:
Type | Description |
---|---|
str
|
The formatted datetime string. |
Examples:
>>> from plantdb.server.rest_api import get_scan_date
>>> from plantdb.commons.test_database import test_database
>>> db = test_database(['real_plant_analyzed', 'virtual_plant_analyzed'])
>>> db.connect()
>>> scan = db.get_scan('real_plant_analyzed')
>>> print(get_scan_date(scan))
>>> scan = db.get_scan('virtual_plant_analyzed')
>>> print(get_scan_date(scan))
>>> db.disconnect()
Source code in plantdb/server/rest_api.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
|
get_scan_info Link
get_scan_info(scan, **kwargs)
Get the information related to a single scan dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scan
|
Scan
|
The scan instance to get information from. |
required |
Other Parameters:
Name | Type | Description |
---|---|---|
logger |
Logger
|
A logger to use with this method, default to a logger created on the fly with a |
Returns:
Type | Description |
---|---|
dict
|
The scan information dictionary. |
Examples:
>>> from plantdb.server.rest_api import get_scan_info
>>> from plantdb.commons.test_database import test_database
>>> db = test_database('real_plant_analyzed')
>>> db.connect()
>>> scan = db.get_scan('real_plant_analyzed')
>>> scan_info = get_scan_info(scan)
>>> print(scan_info)
{'id': 'real_plant_analyzed', 'metadata': {'date': '2023-12-15 16:37:15', 'species': 'N/A', 'plant': 'N/A', 'environment': 'Lyon indoor', 'nbPhotos': 60, 'files': {'metadata': None, 'archive': None}}, 'thumbnailUri': '', 'hasTriangleMesh': True, 'hasPointCloud': True, 'hasPcdGroundTruth': False, 'hasCurveSkeleton': True, 'hasAnglesAndInternodes': True, 'hasSegmentation2D': False, 'hasSegmentedPcdEvaluation': False, 'hasPointCloudEvaluation': False, 'hasManualMeasures': False, 'hasAutomatedMeasures': True, 'hasSegmentedPointCloud': False, 'error': False, 'hasTreeGraph': True}
>>> db.disconnect()
Source code in plantdb/server/rest_api.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
|
get_scan_template Link
get_scan_template(scan_id, error=False)
Template dictionary for a scan.
Source code in plantdb/server/rest_api.py
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 177 178 179 180 181 182 183 184 185 186 |
|
is_within_directory Link
is_within_directory(directory, target)
Check if a target path is within a directory.
This function determines if the absolute path of the target is located
within the absolute path of the directory. It uses os.path.commonpath
to perform the comparison.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
directory
|
str
|
The path to the directory to check against. |
required |
target
|
str
|
The path to the target to check if it resides within the directory. |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in plantdb/server/rest_api.py
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 |
|
rate_limit Link
rate_limit(max_requests=5, window_seconds=60)
Limits the number of requests a client can make within a specified time window.
This function is a decorator that enforces rate limiting based on the maximum
number of allowed requests (max_requests
) and the time window size in seconds
(window_seconds
). It tracks incoming requests from clients using their IP
addresses and ensures that they do not exceed the specified limit within the
time window. If the limit is exceeded, it returns an HTTP 429
response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_requests
|
int
|
The maximum number of requests permitted within the time window (default is 5). |
5
|
window_seconds
|
int
|
The duration of the rate-limiting window in seconds (default is 60 seconds). |
60
|
Returns:
Name | Type | Description |
---|---|---|
decorator |
Callable
|
A decorator that can wrap any function or endpoint to enforce rate limiting. |
Raises:
Type | Description |
---|---|
HTTPException
|
If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client. |
Notes
This implementation uses a thread lock to ensure thread safety when handling
requests, making it suitable for multi-threaded environments. The requests
data structure is a defaultdict
that maps client IPs to a list of their
request timestamps. Old requests outside the rate-limiting window are removed
to maintain efficient memory usage.
Source code in plantdb/server/rest_api.py
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 |
|
sanitize_name Link
sanitize_name(name)
Sanitizes and validates the provided name.
The function ensures that the input string adheres to predefined naming rules by:
- stripping leading/trailing spaces,
- isolating the last segment after splitting by slashes,
- validating the name against an alphanumeric pattern
with optional underscores (
_
), dashes (-
), or periods (.
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name to sanitize and validate. |
required |
Returns:
Type | Description |
---|---|
str
|
A sanitized name that conforms to the rules. |
Raises:
Type | Description |
---|---|
ValueError
|
If the provided name contains invalid characters or does not meet the naming rules. |
Source code in plantdb/server/rest_api.py
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
|