### Development Environment Setup Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Steps to set up a local development environment, including Python version check, virtual environment creation, and installation of development dependencies. ```bash python --version python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ".[dev]" pytest --version mypy --version black --version ruff --version ``` -------------------------------- ### Install OpenF1 Python Client Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This code snippet shows how to install the OpenF1 Python client using pip. It covers standard installation from PyPI, installation from source, and development dependencies. ```bash pip install OpenF1-python-client ``` ```bash git clone https://github.com/rhtnr/OpenF1-python-client.git cd OpenF1-python-client pip install -e . ``` ```bash pip install -e ".[dev]" ``` -------------------------------- ### Example Usage for Bug Reporting Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md A minimal Python code snippet demonstrating how to import and use the OpenF1Client. This serves as a starting point for reproducing bugs. ```python from openf1_client import OpenF1Client # Your code here ``` -------------------------------- ### Clone Repository and Setup Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Instructions for cloning the OpenF1 Python Client repository and setting up the upstream remote. This is a prerequisite for making any contributions. ```bash git clone https://github.com/YOUR_USERNAME/openf1-python.git cd openf1-python git remote add upstream https://github.com/openf1-client/openf1-python.git ``` -------------------------------- ### Google-Style Docstring Example Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md An example of a Python function demonstrating the required Google-style docstring format, including arguments, return values, and potential exceptions. ```python def get_laps(self, session_key: int, driver_number: int) -> list[Lap]: """ Fetch lap data for a specific driver. Args: session_key: The session identifier. driver_number: The driver's car number. Returns: A list of Lap objects for the specified driver. Raises: OpenF1APIError: If the API returns an error response. """ ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This command installs the development dependencies for the openf1-python-client project, including testing and formatting tools. It is typically run from the project's root directory. ```bash pip install -e ".[dev]" ``` -------------------------------- ### OpenF1 Client Usage with Context Manager Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This example showcases the use of a context manager (`with`) to ensure proper client initialization and cleanup. The code retrieves driver information within the context and prints driver names and team affiliations. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get driver information drivers = client.drivers.list(session_key=9158) for driver in drivers: print(f"{driver.name_acronym}: {driver.full_name} - {driver.team_name}") ``` -------------------------------- ### Endpoint Methods Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Demonstrates common methods available for each endpoint, such as listing, getting the first record, and retrieving raw data. ```APIDOC ## Endpoint Methods ### List all matching records ```python laps = client.laps.list(session_key=9161, driver_number=1) ``` ### Get first matching record (or None) ```python lap = client.laps.first(session_key=9161, driver_number=1, lap_number=1) ``` ### Get raw data (dict) without model parsing ```python raw_data = client.laps.list_raw(session_key=9161) ``` ### Get CSV format ```python csv_data = client.laps.list_csv(session_key=9161) ``` ### Count matching records ```python count = client.laps.count(session_key=9161, driver_number=1) ``` ### Convenience Methods (Examples) #### Laps ```python fastest_lap = client.laps.get_fastest_lap(session_key=9161) flying_laps = client.laps.get_flying_laps(session_key=9161, driver_number=1) ``` #### Sessions ```python races = client.sessions.get_races(year=2023) latest = client.sessions.get_latest() ``` #### Stints ```python strategy = client.stints.get_tyre_strategy(session_key=9161, driver_number=1) ``` #### Weather ```python rain = client.weather.get_rain_periods(session_key=9161) ``` ``` -------------------------------- ### Getting Package Version Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md This command displays detailed information about the installed 'openf1-client' package, including its version. This information is crucial for bug reporting. ```bash pip show openf1-client ``` -------------------------------- ### Pytest Example Test Case Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md An example of a Pytest test case that uses the `responses` library to mock HTTP requests for testing the `OpenF1Client`'s ability to fetch driver data. ```python import pytest import responses from openf1_client import OpenF1Client @responses.activate def test_fetch_drivers(): """Test fetching driver data.""" responses.add( responses.GET, "https://api.openf1.org/v1/drivers", json=[{"driver_number": 1, "full_name": "Max Verstappen"}], status=200, ) with OpenF1Client() as client: drivers = client.drivers.list(session_key=9158) assert len(drivers) == 1 assert drivers[0].full_name == "Max Verstappen" ``` -------------------------------- ### Basic Data Retrieval Methods in Python Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Shows common methods available for most endpoints to retrieve data. This includes listing all records, getting the first matching record, fetching raw data, retrieving data as CSV, and counting records. ```python # List all matching records laps = client.laps.list(session_key=9161, driver_number=1) # Get first matching record (or None) lap = client.laps.first(session_key=9161, driver_number=1, lap_number=1) # Get raw data (dict) without model parsing raw_data = client.laps.list_raw(session_key=9161) # Get CSV format csv_data = client.laps.list_csv(session_key=9161) # Count matching records count = client.laps.count(session_key=9161, driver_number=1) ``` -------------------------------- ### Getting Python Version Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md This command prints the currently installed Python version to the console. It is required when reporting bugs to help diagnose environment-specific issues. ```bash python --version ``` -------------------------------- ### Analyze a Race with OpenF1 Data (Python) Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This example illustrates how to analyze a Formula 1 race using the OpenF1Client. It fetches session details, lists all drivers, and then retrieves each driver's fastest lap, pit stop count, and tyre strategy. It requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get session info session = client.sessions.first(session_key=9161) print(f"šŸ Session: {session.session_name} - {session.country_name}") # Get all drivers drivers = client.drivers.list(session_key=9161) for driver in drivers: # Get their fastest lap fastest = client.laps.get_fastest_lap( session_key=9161, driver_number=driver.driver_number, ) # Get pit stops pit_count = client.pit.count_pit_stops( session_key=9161, driver_number=driver.driver_number, ) # Get tyre strategy strategy = client.stints.get_tyre_strategy( session_key=9161, driver_number=driver.driver_number, ) print(f"šŸŽļø {driver.name_acronym}: " f"Fastest: {fastest.lap_duration if fastest else 'N/A'}s, " f"Stops: {pit_count}, " f"Tyres: {' → '.join(strategy)}") ``` -------------------------------- ### Handling OpenF1 Client Errors in Python Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Provides an example of how to use a try-except block to catch and handle various exceptions raised by the `OpenF1Client`. This includes specific errors like `OpenF1NotFoundError`, `OpenF1RateLimitError`, and general errors like `OpenF1APIError` and `OpenF1Error`. ```python from openf1_client import ( OpenF1Client, OpenF1Error, # Base exception OpenF1ConfigError, # Invalid configuration OpenF1TransportError, # Network errors OpenF1APIError, # API errors (non-2xx) OpenF1AuthError, # 401/403 errors OpenF1RateLimitError, # 429 errors OpenF1NotFoundError, # 404 errors OpenF1ServerError, # 5xx errors OpenF1TimeoutError, # Request timeout OpenF1ValidationError, # Data validation ) try: with OpenF1Client() as client: laps = client.laps.list(session_key=99999) except OpenF1NotFoundError as e: print(f"āŒ Session not found: {e}") except OpenF1RateLimitError as e: print(f"ā³ Rate limited. Retry after: {e.retry_after}s") except OpenF1APIError as e: print(f"āš ļø API error {e.status_code}: {e.message}") except OpenF1Error as e: print(f"šŸ’„ Client error: {e}") ``` -------------------------------- ### Find and Count Overtakes in a Race (Python) Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This example demonstrates how to find all overtakes within a session and identify the drivers with the most overtakes. It uses the OpenF1Client to fetch overtake data and the `collections.Counter` to tally occurrences. Requires 'openf1-python-client' and 'collections'. ```python from openf1_client import OpenF1Client from collections import Counter with OpenF1Client() as client: overtakes = client.overtakes.list(session_key=9161) print(f"šŸ”€ Total overtakes: {len(overtakes)}") # Get drivers with most overtakes overtake_counts = Counter(o.driver_number for o in overtakes) print("\nšŸ† Top overtakers:") for driver_num, count in overtake_counts.most_common(5): driver = client.drivers.first( session_key=9161, driver_number=driver_num, ) print(f" {driver.name_acronym}: {count} overtakes") ``` -------------------------------- ### Fetch Session and Race Information with OpenF1Client Sessions Endpoint Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Demonstrates how to use the 'sessions' endpoint of the OpenF1Client to retrieve various types of session and race data. Examples include fetching the latest session, all races for a given year, sessions for a specific meeting, qualifying sessions, and specific practice sessions. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get the latest/current session latest = client.sessions.get_latest() if latest: print(f"{latest.session_name} at {latest.circuit_short_name}") print(f"Started: {latest.date_start}, Ends: {latest.date_end}") # Get all race sessions in 2023 season races_2023 = client.sessions.get_races(year=2023) for race in races_2023: print(f"{race.country_name}: {race.date_start}") # Get all sessions for a specific meeting meeting_sessions = client.sessions.get_for_meeting(meeting_key=1219) for session in meeting_sessions: print(f"{session.session_name}: {session.session_type}") # Get qualifying sessions qualifying = client.sessions.get_qualifying(year=2023) # Get specific practice session fp1 = client.sessions.get_practice( meeting_key=1219, practice_number=1 ) ``` -------------------------------- ### Handle OpenF1 Client Errors with Python Exceptions Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Provides a comprehensive example of error handling for the OpenF1 client library. It demonstrates how to catch specific exceptions like authentication errors, rate limiting, not found, timeouts, validation errors, server errors, and transport errors, as well as base exceptions for broader error management. ```python from openf1_client import ( OpenF1Client, OpenF1Error, OpenF1APIError, OpenF1AuthError, OpenF1NotFoundError, OpenF1RateLimitError, OpenF1ServerError, OpenF1TimeoutError, OpenF1ValidationError, OpenF1ConfigError, OpenF1TransportError ) try: with OpenF1Client(username="user@example.com", password="wrong") as client: # This will fail with auth error client.authenticate() except OpenF1AuthError as e: print(f"Authentication failed: {e.message}") print(f"Status code: {e.status_code}") print(f"URL: {e.request_url}") except OpenF1RateLimitError as e: print(f"Rate limited! Retry after {e.retry_after} seconds") print(f"Response: {e.response_body}") except OpenF1NotFoundError as e: print(f"Resource not found: {e}") except OpenF1TimeoutError as e: print(f"Request timed out after {e.timeout}s") except OpenF1ValidationError as e: print(f"Validation error in field '{e.field}': {e.message}") print(f"Invalid value: {e.value}") except OpenF1ServerError as e: print(f"Server error {e.status_code}: {e.message}") except OpenF1TransportError as e: print(f"Network error: {e}") if e.original_error: print(f"Original error: {e.original_error}") except OpenF1ConfigError as e: print(f"Configuration error: {e.message}") except OpenF1APIError as e: # Catch-all for other API errors print(f"API error {e.status_code}: {e.message}") except OpenF1Error as e: # Base exception for all client errors print(f"OpenF1 client error: {e.message}") ``` -------------------------------- ### Get Driver Information using OpenF1 Python Client Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Retrieves driver metadata such as names, team, nationality, and headshot URLs for a given session. It requires the 'openf1-python-client' library and a valid session key. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get all drivers in a session drivers = client.drivers.list(session_key=9161) for driver in drivers: print(f"#{driver.driver_number}: {driver.full_name} ({driver.name_acronym})") print(f"Team: {driver.team_name} (#{driver.team_colour})") print(f"Country: {driver.country_code}") print(f"Headshot: {driver.headshot_url}") print("---") # Get specific driver information verstappen = client.drivers.first( session_key=9161, driver_number=1 ) if verstappen: print(f"Broadcast name: {verstappen.broadcast_name}") ``` -------------------------------- ### Access CSV and Raw Data - Python Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Retrieve lap data in raw CSV format, parsed CSV dictionaries, or raw JSON without model parsing. This is useful for performance-critical applications or custom data processing. It also demonstrates how to get a count of records without fetching all data. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get data as raw CSV string csv_data = client.laps.list_csv( session_key=9161, driver_number=1 ) # Save to file with open("laps.csv", "w") as f: f.write(csv_data) # Get CSV parsed into dictionaries parsed_csv = client.laps.list_csv_parsed( session_key=9161, driver_number=1 ) for row in parsed_csv: print(row) # Each row is a dict # Get raw JSON data without model validation raw_json = client.laps.list_raw( format="json", session_key=9161, driver_number=1 ) # Process raw dictionaries for item in raw_json: # Custom processing without Pydantic models lap_num = item.get("lap_number") duration = item.get("lap_duration") print(f"Lap {lap_num}: {duration}s") # Get count without fetching all data total_laps = client.laps.count(session_key=9161) print(f"Total laps in session: {total_laps}") ``` -------------------------------- ### Initialize OpenF1Client and Fetch Lap Data Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Demonstrates initializing the OpenF1Client for both unauthenticated and authenticated usage. It shows how to use the client as a context manager for resource cleanup and demonstrates fetching lap data using the 'laps.list' method with session and driver keys. ```python from openf1_client import OpenF1Client # Basic unauthenticated usage for historical data with OpenF1Client() as client: # Get lap data laps = client.laps.list(session_key=9161, driver_number=63) for lap in laps: print(f"Lap {lap.lap_number}: {lap.lap_duration}s") # Authenticated usage with credentials for real-time data client = OpenF1Client( username="user@example.com", password="your_password", timeout=60.0, max_retries=5, verify_ssl=True ) try: # Access authenticated endpoints latest_session = client.sessions.first(session_key="latest") print(f"Current session: {latest_session.session_name}") finally: client.close() # Using pre-existing access token client = OpenF1Client(access_token="your_access_token_here") ``` -------------------------------- ### Configuring the OpenF1Client in Python Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Demonstrates how to instantiate and configure the `OpenF1Client` with various settings including authentication (username/password or token), connection timeouts, retry mechanisms, response format, and SSL verification. ```python from openf1_client import OpenF1Client client = OpenF1Client( # šŸ” Authentication username="user@example.com", password="secret", # Or use a token directly # access_token="your_token", # 🌐 Connection settings timeout=60.0, # Request timeout in seconds # timeout=(5.0, 30.0), # (connect, read) timeouts max_retries=5, # Retry failed requests # šŸ“„ Response format default_format="json", # "json" or "csv" # šŸ”’ SSL/TLS verify_ssl=True, ) ``` -------------------------------- ### Running the Test Suite with Pytest Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Various commands for running the test suite using Pytest, including running all tests, with coverage, specific files, or specific tests, and with verbose output. ```bash # Run all tests pytest # Run with coverage report pytest --cov=openf1_client --cov-report=term-missing # Run specific test file pytest tests/test_client.py # Run specific test pytest tests/test_client.py::TestClientInitialization::test_default_initialization # Run with verbose output pytest -v ``` -------------------------------- ### Enabling Debug Logging for OpenF1 Client in Python Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Shows how to enable debug logging for the `openf1_client` library using the `setup_logging` function or standard Python `logging` configuration. This is useful for inspecting HTTP requests and responses. ```python from openf1_client import setup_logging import logging # Enable debug logging setup_logging(logging.DEBUG) # Or configure manually logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("openf1_client") logger.setLevel(logging.DEBUG) ``` -------------------------------- ### Client Configuration Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Details various configuration options for the `OpenF1Client`, including authentication, connection settings, and response format. ```APIDOC ## Configuration ```python from openf1_client import OpenF1Client client = OpenF1Client( # Authentication username='user@example.com', password='secret', # Or use a token directly # access_token='your_token', # Connection settings timeout=60.0, # Request timeout in seconds # timeout=(5.0, 30.0), # (connect, read) timeouts max_retries=5, # Retry failed requests # Response format default_format='json', # 'json' or 'csv' # SSL/TLS verify_ssl=True, ) ``` ``` -------------------------------- ### Pushing Changes and Creating a Pull Request Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Instructions for pushing your local branch to your fork and creating a pull request on GitHub. This includes details on what to include in the PR description. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Running Code Formatters and Linters Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Commands to format code using Black and lint using Ruff, ensuring adherence to the project's code style guidelines. These should be run before committing changes. ```bash black src tests ruff check src tests --fix ``` -------------------------------- ### Basic Usage of OpenF1 Client Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Demonstrates basic usage of the OpenF1 client to retrieve historical lap data for a specific driver. The code initializes the client, fetches lap data, iterates through the results, and closes the client. ```python from openf1_client import OpenF1Client # Create a client client = OpenF1Client() # Get lap data for a specific driver laps = client.laps.list( session_key=9161, driver_number=63, ) for lap in laps: print(f"Lap {lap.lap_number}: {lap.lap_duration}s") # Don't forget to close the client when done client.close() ``` -------------------------------- ### Logging Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Instructions on how to enable and configure debug logging for the client to monitor requests and responses. ```APIDOC ## Logging Enable debug logging to see HTTP requests and responses: ```python from openf1_client import setup_logging import logging # Enable debug logging setup_logging(logging.DEBUG) # Or configure manually logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('openf1_client') logger.setLevel(logging.DEBUG) ``` ``` -------------------------------- ### Authenticated OpenF1 Client Usage Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Demonstrates authenticating with OpenF1 using credentials and an access token. The code retrieves the current session information and prints the session name, or uses a pre-existing access token. ```python from openf1_client import OpenF1Client client = OpenF1Client( username="your_email@example.com", password="your_password", ) # Access real-time data latest_session = client.sessions.first(session_key="latest") print(f"Current session: {latest_session.session_name}" ``` ```python client = OpenF1Client(access_token="your_access_token") ``` -------------------------------- ### Convenience Methods for Specific Data in Python Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Highlights specialized convenience methods for retrieving specific types of data, such as the fastest lap, flying laps, races for a given year, the latest session, tyre strategies, and rain periods. ```python # šŸ”„ Laps fastest_lap = client.laps.get_fastest_lap(session_key=9161) flying_laps = client.laps.get_flying_laps(session_key=9161, driver_number=1) # šŸ“… Sessions races = client.sessions.get_races(year=2023) latest = client.sessions.get_latest() # šŸ”§ Stints strategy = client.stints.get_tyre_strategy(session_key=9161, driver_number=1) # šŸŒ¤ļø Weather rain = client.weather.get_rain_periods(session_key=9161) ``` -------------------------------- ### Using FilterBuilder Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Illustrates the use of `FilterBuilder` for constructing complex filter criteria. ```APIDOC ## Using FilterBuilder For more complex filters, use the `FilterBuilder` helper: ```python from openf1_client import OpenF1Client, FilterBuilder with OpenF1Client() as client: filters = ( FilterBuilder() .eq('session_key', 9161) .eq('driver_number', 1) .gte('speed', 300) .lt('lap_number', 10) .build() ) car_data = client.car_data.list(**filters) ``` ``` -------------------------------- ### Parse Lap Data with Pydantic Models (Python) Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This snippet demonstrates how to fetch a specific lap's data using the OpenF1Client and parse the response into a Pydantic Lap model. It shows how to access detailed lap metrics like duration and sector times. Requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client, Lap, Driver with OpenF1Client() as client: lap: Lap = client.laps.first(session_key=9161, driver_number=1, lap_number=1) if lap: print(f"Lap duration: {lap.lap_duration}") print(f"Sector 1: {lap.duration_sector_1}") print(f"Sector 2: {lap.duration_sector_2}") print(f"Sector 3: {lap.duration_sector_3}") print(f"Speed trap: {lap.st_speed} km/h") ``` -------------------------------- ### Available Endpoints Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Lists all available endpoints for retrieving different types of Formula 1 data. ```APIDOC ## Available Endpoints | Endpoint | Description | |----------|-------------| | `car_data` | Car telemetry (~3.7 Hz) | | `drivers` | Driver information | | `intervals` | Gap data (~4s updates) | | `laps` | Lap timing data | | `location` | Car positions (~3.7 Hz) | | `meetings` | Grand Prix metadata | | `overtakes` | Passing events (beta) | | `pit` | Pit stop activity | | `position` | Track positions | | `race_control` | Flags, incidents | | `sessions` | Session data | | `session_result` | Final results (beta) | | `starting_grid` | Grid positions (beta) | | `stints` | Stint/tyre data | | `team_radio` | Radio communications | | `weather` | Weather data (~1 min) | ``` -------------------------------- ### Running Project Checks with pytest Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md This command executes all tests in the project using the pytest framework. Ensure all tests pass before submitting a pull request to maintain code quality and prevent regressions. ```bash pytest ``` -------------------------------- ### Formatting Code with black Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md This command formats the Python code within the 'src' and 'tests' directories using the black code formatter. Consistent code style is essential for readability and maintainability. ```bash black src tests ``` -------------------------------- ### Linting Code with ruff Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md This command runs the ruff linter on the 'src' and 'tests' directories to check for code style violations and potential errors. Linting helps enforce code quality standards. ```bash ruff check src tests ``` -------------------------------- ### Running Type Checking with Mypy Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Command to run Mypy for static type checking on the client's source code. This helps ensure type safety and catches potential type-related errors. ```bash mypy src/openf1_client ``` -------------------------------- ### Configure Logging - Python Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Enable and configure detailed logging for the OpenF1 client to assist with debugging. This includes setting log levels (e.g., DEBUG) and customizing the log message format. Logs can show HTTP requests, responses, retries, and validation steps. ```python from openf1_client import OpenF1Client, setup_logging import logging # Enable debug logging setup_logging(logging.DEBUG) # Or configure manually with custom format logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("openf1_client") logger.setLevel(logging.DEBUG) # Now all client operations will log detailed information with OpenF1Client() as client: # This will log the HTTP request and response details laps = client.laps.list(session_key=9161, driver_number=1) # Logs will show: # - Request URL with query parameters # - Request headers # - Response status code # - Response body (with sensitive data redacted) # - Retry attempts # - Validation steps ``` -------------------------------- ### Access Tyre Stint Data using OpenF1 Python Client Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Provides access to driver stint information, including tyre compounds, age, and lap ranges. Allows fetching all stints for a driver, tyre strategy summaries, and identifying drivers by tyre compound. Requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get all stints for a driver stints = client.stints.get_driver_stints( session_key=9161, driver_number=1 ) for stint in stints: print(f"Stint {stint.stint_number}: {stint.compound}") print(f"Laps {stint.lap_start} to {stint.lap_end}") print(f"Tyre age at start: {stint.tyre_age_at_start} laps") print("---") # Get tyre strategy summary strategy = client.stints.get_tyre_strategy( session_key=9161, driver_number=1 ) print(f"Strategy: {' → '.join(strategy)}") # Find all drivers who used soft tyres soft_stints = client.stints.get_by_compound( session_key=9161, compound="SOFT" ) unique_drivers = set(s.driver_number for s in soft_stints) print(f"Drivers on soft tyres: {unique_drivers}") ``` -------------------------------- ### Creating a New Feature Branch Source: https://github.com/rhtnr/openf1-python-client/blob/main/CONTRIBUTING.md Commands to create a new Git branch for developing a new feature or fixing a bug. This follows standard Git branching practices. ```bash git checkout -b feature/your-feature-name # or git checkout -b fix/your-bug-fix ``` -------------------------------- ### Range Filters Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Shows how to apply date and lap number range filters when fetching data. ```APIDOC ## Range Filters ### Date range ```python location_data = client.location.list( session_key=9161, driver_number=81, date={'>': '2023-09-16T13:03:35.200', '<': '2023-09-16T13:03:35.800'}, ) ``` ### Lap range ```python stint_laps = client.laps.list( session_key=9161, driver_number=1, lap_number={'>=': 10, '<=': 20}, ) ``` ``` -------------------------------- ### Error Handling Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Explains the exception hierarchy provided by the client for handling various API and network errors. ```APIDOC ## Error Handling The client provides a comprehensive exception hierarchy: ```python from openf1_client import ( OpenF1Client, OpenF1Error, # Base exception OpenF1ConfigError, # Invalid configuration OpenF1TransportError, # Network errors OpenF1APIError, # API errors (non-2xx) OpenF1AuthError, # 401/403 errors OpenF1RateLimitError, # 429 errors OpenF1NotFoundError, # 404 errors OpenF1ServerError, # 5xx errors OpenF1TimeoutError, # Request timeout OpenF1ValidationError, # Data validation ) try: with OpenF1Client() as client: laps = client.laps.list(session_key=99999) except OpenF1NotFoundError as e: print(f'āŒ Session not found: {e}') except OpenF1RateLimitError as e: print(f'ā³ Rate limited. Retry after: {e.retry_after}s') except OpenF1APIError as e: print(f'āš ļø API error {e.status_code}: {e.message}') except OpenF1Error as e: print(f'šŸ’„ Client error: {e}') ``` ``` -------------------------------- ### Retrieve Weather and Track Conditions with OpenF1 Python Client Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Fetches environmental data like air temperature, track temperature, humidity, pressure, and wind conditions updated approximately every minute. Supports filtering for specific conditions, such as periods with rain. Requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get all weather data for a session weather_data = client.weather.list(session_key=9161) for w in weather_data: rain_status = "šŸŒ§ļø RAIN" if w.rainfall else "ā˜€ļø DRY" print(f"{rain_status} at {w.date}") print(f"Air temp: {w.air_temperature}°C") print(f"Track temp: {w.track_temperature}°C") print(f"Humidity: {w.humidity}%") print(f"Pressure: {w.pressure} mbar") print(f"Wind: {w.wind_speed} m/s at {w.wind_direction}°") print("---") # Find periods with rain rainy_periods = [w for w in weather_data if w.rainfall] if rainy_periods: print(f"Rain detected at {len(rainy_periods)} measurement points") ``` -------------------------------- ### Fetch Detailed Lap Timing Data with OpenF1Client Laps Endpoint Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Illustrates using the 'laps' endpoint of the OpenF1Client to retrieve detailed lap timing information. It covers fetching all laps for a driver, the fastest lap, laps within a range, laps matching specific duration criteria, and flying laps. ```python from openf1_client import OpenF1Client, OpenF1NotFoundError with OpenF1Client() as client: # Get all laps for a specific driver in a session laps = client.laps.list( session_key=9161, driver_number=63 ) # Get fastest lap in the session fastest = client.laps.get_fastest_lap(session_key=9161) if fastest: print(f"Fastest lap: {fastest.lap_duration}s by driver #{fastest.driver_number}") print(f"Sector times: S1={fastest.duration_sector_1}s, " f"S2={fastest.duration_sector_2}s, S3={fastest.duration_sector_3}s") print(f"Speed trap: {fastest.st_speed} km/h") # Get laps within a specific range stint_laps = client.laps.get_lap_range( session_key=9161, driver_number=1, start_lap=10, end_lap=20 ) # Get fast laps under 90 seconds using comparison operator fast_laps = client.laps.list( session_key=9161, lap_duration={"<": 90.0} ) # Get flying laps only (exclude pit out laps) flying = client.laps.get_flying_laps(session_key=9161, driver_number=1) ``` -------------------------------- ### Filtering OpenF1 Data - Comparison Operators Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md Demonstrates filtering data using comparison operators such as greater than or equal to, and less than. The code retrieves telemetry data based on speed and intervals based on time differences. ```python # Speed >= 315 km/h fast_telemetry = client.car_data.list( session_key=9159, driver_number=55, speed={">=": 315}, ) ``` ```python # Close intervals (< 0.5 seconds) close_battles = client.intervals.list( session_key=9161, interval={"<": 0.5}, ) ``` -------------------------------- ### Track Weather Changes During a Session (Python) Source: https://github.com/rhtnr/openf1-python-client/blob/main/README.md This Python snippet shows how to retrieve and display weather data for a specific Formula 1 session using the OpenF1Client. It iterates through weather data points, printing the date, air temperature, track temperature, and humidity. Requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: weather_data = client.weather.list(session_key=9161) for w in weather_data: rain_emoji = "šŸŒ§ļø" if w.rainfall else "ā˜€ļø" print(f"{rain_emoji} {w.date}") print(f" šŸŒ”ļø Air: {w.air_temperature}°C") print(f" šŸ›£ļø Track: {w.track_temperature}°C") print(f" šŸ’§ Humidity: {w.humidity}%") ``` -------------------------------- ### Error Handling - Comprehensive Exception Management Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Handle various API error conditions with a rich exception hierarchy that provides detailed error context and retry information. ```APIDOC ## Error Handling ### Description Provides a comprehensive hierarchy of exceptions for handling various error conditions encountered when using the OpenF1 client, including authentication, rate limiting, validation, and server errors. ### Method N/A (Exception classes) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from openf1_client import ( OpenF1Client, OpenF1Error, OpenF1APIError, OpenF1AuthError, OpenF1NotFoundError, OpenF1RateLimitError, OpenF1ServerError, OpenF1TimeoutError, OpenF1ValidationError, OpenF1ConfigError, OpenF1TransportError ) try: with OpenF1Client(username="user@example.com", password="wrong") as client: # This will fail with auth error client.authenticate() except OpenF1AuthError as e: print(f"Authentication failed: {e.message}") print(f"Status code: {e.status_code}") print(f"URL: {e.request_url}") except OpenF1RateLimitError as e: print(f"Rate limited! Retry after {e.retry_after} seconds") print(f"Response: {e.response_body}") except OpenF1NotFoundError as e: print(f"Resource not found: {e}") except OpenF1TimeoutError as e: print(f"Request timed out after {e.timeout}s") except OpenF1ValidationError as e: print(f"Validation error in field '{e.field}': {e.message}") print(f"Invalid value: {e.value}") except OpenF1ServerError as e: print(f"Server error {e.status_code}: {e.message}") except OpenF1TransportError as e: print(f"Network error: {e}") if e.original_error: print(f"Original error: {e.original_error}") except OpenF1ConfigError as e: print(f"Configuration error: {e.message}") except OpenF1APIError as e: # Catch-all for other API errors print(f"API error {e.status_code}: {e.message}") except OpenF1Error as e: # Base exception for all client errors print(f"OpenF1 client error: {e.message}") ``` ### Exception Hierarchy - **OpenF1Error**: Base class for all OpenF1 client errors. - **OpenF1ConfigError**: Errors related to client configuration. - **OpenF1TransportError**: Network or transport-level errors. - **original_error**: The underlying exception if available. - **OpenF1APIError**: Base class for API-specific errors. - **OpenF1AuthError**: Authentication failed. - **message**: Error message. - **status_code**: HTTP status code. - **request_url**: The URL that failed. - **OpenF1NotFoundError**: Requested resource not found. - **OpenF1RateLimitError**: API rate limit exceeded. - **retry_after**: Seconds to wait before retrying. - **response_body**: The response body from the server. - **OpenF1ServerError**: Server-side error occurred. - **status_code**: HTTP status code. - **message**: Error message. - **OpenF1TimeoutError**: Request timed out. - **timeout**: The timeout duration in seconds. - **OpenF1ValidationError**: Data validation failed. - **field**: The field that failed validation. - **value**: The invalid value. - **message**: Error message. ### Response N/A (This section describes exception handling, not API responses) ### Response Example N/A ``` -------------------------------- ### Retrieve Interval Data with Python Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Fetches interval data, including gap to the leader and time to the car ahead, for a given session. This data is typically updated every few seconds. It also demonstrates how to filter for close battles based on small time gaps. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get current intervals for all drivers intervals = client.intervals.list(session_key=9161) for interval in intervals: print(f"Driver #{interval.driver_number}") print(f"Gap to leader: {interval.gap_to_leader}s") print(f"Interval to car ahead: {interval.interval}s") print("---") # Find close battles (gaps less than 0.5 seconds) close_battles = client.intervals.list( session_key=9161, interval={"<": 0.5, ">": 0} ) print(f"Found {len(close_battles)} close battles on track") ``` -------------------------------- ### Access Pit Stop Data using OpenF1 Python Client Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Retrieves pit stop activity details, including entry times, duration, and lap numbers. Allows fetching all pit stops for a driver, counting total pit stops, and filtering for fast pit stops. Requires the 'openf1-python-client' library. ```python from openf1_client import OpenF1Client with OpenF1Client() as client: # Get all pit stops for a driver pit_stops = client.pit.list( session_key=9161, driver_number=1 ) for stop in pit_stops: print(f"Lap {stop.lap_number}: {stop.pit_duration}s") print(f"Time: {stop.date}") # Count total pit stops pit_count = client.pit.count(session_key=9161, driver_number=1) print(f"Total pit stops: {pit_count}") # Find fast pit stops (under 3 seconds) fast_stops = client.pit.list( session_key=9161, pit_duration={ '<': 3.0} ) ``` -------------------------------- ### Build Complex Filters with FilterBuilder in Python Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Demonstrates the use of the FilterBuilder class to construct complex query filters programmatically. This fluent interface allows for chaining comparison operators to specify criteria for fetching data from various endpoints, such as car data or lap information. It also shows how to reuse and clear the builder. ```python from openf1_client import OpenF1Client, FilterBuilder with OpenF1Client() as client: # Build complex filter using fluent interface filters = ( FilterBuilder() .eq("session_key", 9161) .eq("driver_number", 1) .gte("speed", 300) .lte("speed", 330) .gte("lap_number", 5) .lt("lap_number", 15) .build() ) # Use filters with any endpoint car_data = client.car_data.list(**filters) print(f"Found {len(car_data)} telemetry samples matching criteria") # Range filter example lap_filters = ( FilterBuilder() .eq("session_key", 9161) .eq("driver_number", 44) .between("lap_duration", 85.0, 90.0, inclusive=True) .build() ) laps = client.laps.list(**lap_filters) # Clear and reuse builder builder = FilterBuilder() filters1 = builder.eq("session_key", 9161).build() filters2 = builder.clear().eq("session_key", 9162).build() ``` -------------------------------- ### FilterBuilder - Advanced Query Construction Source: https://context7.com/rhtnr/openf1-python-client/llms.txt Construct complex filters programmatically using a fluent builder interface with various comparison operators for querying data. ```APIDOC ## FilterBuilder ### Description A utility class for programmatically constructing complex query filters with a fluent interface. ### Method N/A (Class methods) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from openf1_client import OpenF1Client, FilterBuilder with OpenF1Client() as client: # Build complex filter using fluent interface filters = ( FilterBuilder() .eq("session_key", 9161) .eq("driver_number", 1) .gte("speed", 300) .lte("speed", 330) .gte("lap_number", 5) .lt("lap_number", 15) .build() ) # Use filters with any endpoint car_data = client.car_data.list(**filters) print(f"Found {len(car_data)} telemetry samples matching criteria") # Range filter example lap_filters = ( FilterBuilder() .eq("session_key", 9161) .eq("driver_number", 44) .between("lap_duration", 85.0, 90.0, inclusive=True) .build() ) laps = client.laps.list(**lap_filters) # Clear and reuse builder builder = FilterBuilder() filters1 = builder.eq("session_key", 9161).build() filters2 = builder.clear().eq("session_key", 9162).build() ``` ### Available Filter Methods - **eq**(field, value): Equals - **neq**(field, value): Not Equals - **gt**(field, value): Greater Than - **gte**(field, value): Greater Than or Equals - **lt**(field, value): Less Than - **lte**(field, value): Less Than or Equals - **in**(field, values): In a list of values - **nin**(field, values): Not In a list of values - **between**(field, lower, upper, inclusive=False): Between two values - **like**(field, pattern): Pattern matching (SQL LIKE) - **ilike**(field, pattern): Case-insensitive pattern matching - **is_null**(field): Is NULL - **is_not_null**(field): Is NOT NULL ### Response N/A (This is a builder class, not an endpoint) ### Response Example N/A ```