A Python wrapper for the iRail API
Project description
pyRail
An async Python wrapper for the iRail API, designed to make interacting with iRail simple and efficient. Built with aiohttp, it provides non-blocking I/O operations for optimal performance in async applications.
Overview
pyRail is a Python library that provides a convenient interface for interacting with the iRail API. It supports various endpoints such as stations, liveboard, vehicle, connections, and disturbances. The library includes features like caching and rate limiting to optimize API usage.
Features
- Async handling
- Retrieve real-time train information, including liveboards and vehicle details.
- Access train station data, connections, and disturbances.
- Supports API endpoints: stations, liveboard, vehicle, connections, and disturbances.
- Caching and conditional GET requests using ETags.
- Rate limiting to handle API request limits efficiently.
Installation
To install pyRail, use pip:
pip install pyrail
Usage
Here is an example of how to use pyRail asynchronously:
import asyncio
from pyrail.irail import iRail
async def main():
# Sequential requests example
async with iRail() as api:
try:
# Get the total number of stations
stations = await api.get_stations()
if stations:
print(f"Total stations: {len(stations)}")
# Example output: Total stations: 691
# stations = [
# {"name": "Brussels-South", "id": "BE.NMBS.008814001", ...},
# ...
# ]
# Get the liveboard for a specific station
liveboard = await api.get_liveboard(station='Brussels-South')
if liveboard:
print(f"Liveboard for Brussels-South: {liveboard}")
except Exception as e:
print(f"Error occurred: {e}")
# Parallel requests example
async with iRail() as api:
try:
connections, vehicle_info = await asyncio.gather(
# Get connections between stations
api.get_connections(
from_station='Antwerpen-Centraal',
to_station='Brussel-Centraal'
),
# Get vehicle information
api.get_vehicle("BE.NMBS.IC1832")
)
print("Parallel results:")
print(f"Connections from Antwerpen-Centraal to Brussel-Centraal: {connections}")
print(f"Vehicle information for BE.NMBS.IC1832: {vehicle_info}")
except Exception as e:
print(f"Error occurred in parallel requests: {e}")
# Run the async code
if __name__ == "__main__":
asyncio.run(main())
Language Selection
You can configure the language for the API requests:
api = iRail(lang='nl')
Supported languages are:
en(English, default)fr(French)de(German)nl(Dutch)
If no language is specified or an invalid value is provided, English (en) will be used as the default language.
Session Management
You can provide an external aiohttp ClientSession:
from aiohttp import ClientSession
async def main():
# Using an external session
async with ClientSession() as session:
async with iRail(session=session) as api:
stations = await api.get_stations()
print(f"Total stations: {len(stations)}")
# Or let iRail manage its own session
async with iRail() as api:
stations = await api.get_stations()
Cache Management
You can clear the ETag cache when needed:
async with iRail() as api:
# Clear the ETag cache
api.clear_etag_cache()
# Subsequent requests will fetch fresh data
stations = await api.get_stations()
Rate Limiting
pyRail implements rate limiting to comply with iRail API's guidelines:
- Maximum of 3 requests per second per source IP address
- 5 burst requests available, allowing up to 8 requests in 1 second
The library automatically handles rate limiting:
# Rate limiting is handled automatically
async with iRail() as api:
# These requests will be rate-limited if needed
for station in ['Brussels-South', 'Antwerp-Central', 'Ghent-Sint-Pieters']:
liveboard = await api.get_liveboard(station=station)
Exceeding the request limit will cause the server to return 429 responses. You can monitor rate limiting through debug logs.
Development
The devcontainer setup includes all necessary dependencies and tools for development.
Prerequisites
- Docker
- Visual Studio Code
- Remote - Containers extension
Setup
- Clone the repository:
git clone https://github.com/tjorim/pyrail.git
- Open the project in a devcontainer:
cd pyrail code .
- Once VS Code opens, it will detect the devcontainer configuration and prompt you to reopen the project in a container. Click "Reopen in Container" to start the development environment.
Running Tests
To run the tests, use the following command in the terminal within the devcontainer:
pytest
Code Style
We use ruff for code formatting and linting. To check your code style, run:
ruff check .
To automatically fix style issues, run:
ruff check . --fix
Logging
pyRail uses Python's built-in logging module. You can set the logging level at runtime to get detailed logs.
import logging
# Set the logging level to DEBUG
logging.basicConfig(level=logging.DEBUG)
Contributing
Contributions are welcome! Here's how you can contribute to pyRail:
Issue Reporting
- Use the GitHub issue tracker to report bugs or suggest features.
- Check existing issues before opening a new one.
- Provide as much detail as possible, including steps to reproduce for bugs.
Pull Requests
- Fork the repository and create your branch from
main. - Ensure your code adheres to the project's style guidelines (run
ruff check .). - Add or update tests as necessary.
- Update documentation to reflect your changes.
- Submit a pull request with a clear title and description.
- Your pull request will be automatically reviewed by CodeRabbit for code quality and consistency.
Contributors
- @tjorim
- @jcoetsie
- @lgnap
License
This project is licensed under the Apache 2.0 License. See the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyrail-0.4.1.tar.gz.
File metadata
- Download URL: pyrail-0.4.1.tar.gz
- Upload date:
- Size: 19.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.12.9 Linux/6.8.0-1021-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1e685350cb4c76024980baf68a302ab3cacb80420799cdddb289b32556330811
|
|
| MD5 |
cede751339aea8c3cda6d0e5e0dc135c
|
|
| BLAKE2b-256 |
f69e1fb9cf702fac8cbd82362fb110731001bf115df4f48bdfc1b4f193b3377e
|
File details
Details for the file pyrail-0.4.1-py3-none-any.whl.
File metadata
- Download URL: pyrail-0.4.1-py3-none-any.whl
- Upload date:
- Size: 18.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.12.9 Linux/6.8.0-1021-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d18226bdcd83d5381e5021376568147871e54773c7aa5a2ad4d58864735ee8be
|
|
| MD5 |
b7855f17abcdd388186eaac1631a065a
|
|
| BLAKE2b-256 |
aa5ae4251f0cd64080aed7c0d726f682f50a1337ad850088b845de0a7f69821c
|