From 686e4ff47720de2fe0ad10f08699c661d348589c Mon Sep 17 00:00:00 2001 From: Matteo Rosati Date: Fri, 16 Jan 2026 08:55:18 +0100 Subject: [PATCH] add limit --- app.py | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/app.py b/app.py index 1a1d4b7..097aba5 100644 --- a/app.py +++ b/app.py @@ -160,14 +160,16 @@ def plext_to_dict(plext: Plext) -> dict: def get_plexts_from_db(): """ Get plexts from MongoDB with optional filters. + Returns plexts sorted by timestamp (most recent first). Query Parameters: player_name: Filter by player name (optional) timestamp_from: Minimum timestamp in milliseconds (optional) timestamp_to: Maximum timestamp in milliseconds (optional) + limit: Maximum number of results to return (optional, default: 100) Returns: - JSON response with list of plexts (without _id field) + JSON response with list of plexts (without _id field), limited by the limit parameter """ # CORS headers cors_headers = { @@ -185,6 +187,7 @@ def get_plexts_from_db(): player_name = request.args.get("player_name") timestamp_from = request.args.get("timestamp_from") timestamp_to = request.args.get("timestamp_to") + limit_param = request.args.get("limit") # Validate and convert timestamp parameters to integers if provided if timestamp_from is not None: @@ -207,6 +210,25 @@ def get_plexts_from_db(): cors_headers, ) + # Validate and convert limit parameter to integer if provided, otherwise default to 100 + if limit_param is not None: + try: + limit = int(limit_param) + if limit <= 0: + return ( + jsonify({"error": "limit must be a positive integer"}), + 400, + cors_headers, + ) + except ValueError: + return ( + jsonify({"error": "limit must be an integer"}), + 400, + cors_headers, + ) + else: + limit = 100 + # Build MongoDB filter query filter_query = {} @@ -234,9 +256,11 @@ def get_plexts_from_db(): # Projection to exclude _id field projection = {"_id": 0} - # Execute query with sorting (timestamp DESC - most recent first) - cursor = collection.find(filter=filter_query, projection=projection).sort( - "timestamp", -1 + # Execute query with sorting (timestamp DESC - most recent first) and dynamic limit + cursor = ( + collection.find(filter=filter_query, projection=projection) + .sort("timestamp", -1) + .limit(limit) ) # Convert cursor to list @@ -369,11 +393,12 @@ def index(): }, "/plexts/from-db": { "method": "GET", - "description": "Get plexts from MongoDB with optional filters", + "description": "Get plexts from MongoDB with optional filters. Returns plexts sorted by timestamp (most recent first).", "parameters": { "player_name": "Filter by player name (optional)", "timestamp_from": "Minimum timestamp in milliseconds (optional)", "timestamp_to": "Maximum timestamp in milliseconds (optional)", + "limit": "Maximum number of results to return (optional, default: 100)", }, "authentication": "Basic Auth required", },