# 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:
```bash
pip install pyrail
```
## Usage
Here is an example of how to use pyRail asynchronously:
```python
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:
```python
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:
```python
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:
```python
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:
```python
# 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
1. Clone the repository:
```bash
git clone https://github.com/tjorim/pyrail.git
```
2. Open the project in a devcontainer:
```bash
cd pyrail
code .
```
3. 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:
```bash
pytest
```
### Code Style
We use ruff for code formatting and linting. To check your code style, run:
```bash
ruff check .
```
To automatically fix style issues, run:
```bash
ruff check . --fix
```
## Logging
pyRail uses Python's built-in logging module. You can set the logging level at runtime to get detailed logs.
```python
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
1. Fork the repository and create your branch from `main`.
2. Ensure your code adheres to the project's style guidelines (run `ruff check .`).
3. Add or update tests as necessary.
4. Update documentation to reflect your changes.
5. Submit a pull request with a clear title and description.
6. 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.
Raw data
{
"_id": null,
"home_page": "https://github.com/tjorim/pyrail",
"name": "pyrail",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.12",
"maintainer_email": null,
"keywords": "irail, nmbs",
"author": "Jorim Tielemans",
"author_email": "tielemans.jorim@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/5b/7b/f86d8453d75245b6b19ec63f69f8aeb3bd69565845760cbdae8a04b97a78/pyrail-0.4.0.tar.gz",
"platform": null,
"description": "# pyRail\n\nAn async Python wrapper for the iRail API, designed to make interacting with iRail simple and efficient.\nBuilt with aiohttp, it provides non-blocking I/O operations for optimal performance in async applications.\n\n## Overview\n\npyRail 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.\n\n## Features\n\n- Async handling\n- Retrieve real-time train information, including liveboards and vehicle details.\n- Access train station data, connections, and disturbances.\n- Supports API endpoints: stations, liveboard, vehicle, connections, and disturbances.\n- Caching and conditional GET requests using ETags.\n- Rate limiting to handle API request limits efficiently.\n\n## Installation\n\nTo install pyRail, use pip:\n\n```bash\npip install pyrail\n```\n\n## Usage\n\nHere is an example of how to use pyRail asynchronously:\n\n```python\nimport asyncio\nfrom pyrail.irail import iRail\n\nasync def main():\n # Sequential requests example\n async with iRail() as api:\n try:\n # Get the total number of stations\n stations = await api.get_stations()\n if stations:\n print(f\"Total stations: {len(stations)}\")\n # Example output: Total stations: 691\n # stations = [\n # {\"name\": \"Brussels-South\", \"id\": \"BE.NMBS.008814001\", ...},\n # ...\n # ]\n # Get the liveboard for a specific station\n liveboard = await api.get_liveboard(station='Brussels-South')\n if liveboard:\n print(f\"Liveboard for Brussels-South: {liveboard}\")\n except Exception as e:\n print(f\"Error occurred: {e}\")\n # Parallel requests example\n async with iRail() as api:\n try:\n connections, vehicle_info = await asyncio.gather(\n # Get connections between stations\n api.get_connections(\n from_station='Antwerpen-Centraal',\n to_station='Brussel-Centraal'\n ),\n # Get vehicle information\n api.get_vehicle(\"BE.NMBS.IC1832\")\n )\n print(\"Parallel results:\")\n print(f\"Connections from Antwerpen-Centraal to Brussel-Centraal: {connections}\")\n print(f\"Vehicle information for BE.NMBS.IC1832: {vehicle_info}\")\n except Exception as e:\n print(f\"Error occurred in parallel requests: {e}\")\n\n# Run the async code\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\n### Language Selection\n\nYou can configure the language for the API requests:\n\n```python\napi = iRail(lang='nl')\n```\n\nSupported languages are:\n\n- `en` (English, default)\n- `fr` (French)\n- `de` (German)\n- `nl` (Dutch)\n\nIf no language is specified or an invalid value is provided, English (`en`) will be used as the default language.\n\n### Session Management\n\nYou can provide an external aiohttp ClientSession:\n\n```python\nfrom aiohttp import ClientSession\n\nasync def main():\n # Using an external session\n async with ClientSession() as session:\n async with iRail(session=session) as api:\n stations = await api.get_stations()\n print(f\"Total stations: {len(stations)}\")\n\n # Or let iRail manage its own session\n async with iRail() as api:\n stations = await api.get_stations()\n```\n\n### Cache Management\n\nYou can clear the ETag cache when needed:\n\n```python\nasync with iRail() as api:\n # Clear the ETag cache\n api.clear_etag_cache()\n # Subsequent requests will fetch fresh data\n stations = await api.get_stations()\n```\n\n### Rate Limiting\n\npyRail implements rate limiting to comply with iRail API's guidelines:\n\n- Maximum of 3 requests per second per source IP address\n- 5 burst requests available, allowing up to 8 requests in 1 second\n\nThe library automatically handles rate limiting:\n\n```python\n# Rate limiting is handled automatically\nasync with iRail() as api:\n # These requests will be rate-limited if needed\n for station in ['Brussels-South', 'Antwerp-Central', 'Ghent-Sint-Pieters']:\n liveboard = await api.get_liveboard(station=station)\n```\n\nExceeding the request limit will cause the server to return 429 responses. You can monitor rate limiting through debug logs.\n\n## Development\n\nThe devcontainer setup includes all necessary dependencies and tools for development.\n\n### Prerequisites\n\n- Docker\n- Visual Studio Code\n- Remote - Containers extension\n\n### Setup\n\n1. Clone the repository:\n ```bash\n git clone https://github.com/tjorim/pyrail.git\n ```\n2. Open the project in a devcontainer:\n ```bash\n cd pyrail\n code .\n ```\n3. 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.\n\n### Running Tests\n\nTo run the tests, use the following command in the terminal within the devcontainer:\n\n```bash\npytest\n```\n\n### Code Style\n\nWe use ruff for code formatting and linting. To check your code style, run:\n\n```bash\nruff check .\n```\n\nTo automatically fix style issues, run:\n\n```bash\nruff check . --fix\n```\n\n## Logging\n\npyRail uses Python's built-in logging module. You can set the logging level at runtime to get detailed logs.\n\n```python\nimport logging\n\n# Set the logging level to DEBUG\nlogging.basicConfig(level=logging.DEBUG)\n```\n\n## Contributing\n\nContributions are welcome! Here's how you can contribute to pyRail:\n\n### Issue Reporting\n\n- Use the GitHub issue tracker to report bugs or suggest features.\n- Check existing issues before opening a new one.\n- Provide as much detail as possible, including steps to reproduce for bugs.\n\n### Pull Requests\n\n1. Fork the repository and create your branch from `main`.\n2. Ensure your code adheres to the project's style guidelines (run `ruff check .`).\n3. Add or update tests as necessary.\n4. Update documentation to reflect your changes.\n5. Submit a pull request with a clear title and description.\n6. Your pull request will be automatically reviewed by CodeRabbit for code quality and consistency.\n\n## Contributors\n\n- @tjorim\n- @jcoetsie\n- @lgnap\n\n## License\n\nThis project is licensed under the Apache 2.0 License. See the LICENSE file for details.\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "A Python wrapper for the iRail API",
"version": "0.4.0",
"project_urls": {
"Documentation": "https://github.com/tjorim/pyrail",
"Homepage": "https://github.com/tjorim/pyrail",
"Repository": "https://github.com/tjorim/pyrail"
},
"split_keywords": [
"irail",
" nmbs"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "84fc37ea4a5bd7a9b9460a06f69e69ad24692cd3d404f3b64eb73b10cffe537b",
"md5": "071604ecd43901fe68ac07ed9798092d",
"sha256": "ddf244fa3bfc93aa05f7263007090e38ab0b4b260ea1935722fdf5446a2242b3"
},
"downloads": -1,
"filename": "pyrail-0.4.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "071604ecd43901fe68ac07ed9798092d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.12",
"size": 18031,
"upload_time": "2025-01-28T00:42:15",
"upload_time_iso_8601": "2025-01-28T00:42:15.283189Z",
"url": "https://files.pythonhosted.org/packages/84/fc/37ea4a5bd7a9b9460a06f69e69ad24692cd3d404f3b64eb73b10cffe537b/pyrail-0.4.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "5b7bf86d8453d75245b6b19ec63f69f8aeb3bd69565845760cbdae8a04b97a78",
"md5": "eb1b6a86d3f5bcaeff23f1af92277552",
"sha256": "b7088d42ccd03116e211e81893baf0fe6e337b5453f17e5de34f6d5c6b9be035"
},
"downloads": -1,
"filename": "pyrail-0.4.0.tar.gz",
"has_sig": false,
"md5_digest": "eb1b6a86d3f5bcaeff23f1af92277552",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.12",
"size": 19012,
"upload_time": "2025-01-28T00:42:17",
"upload_time_iso_8601": "2025-01-28T00:42:17.047280Z",
"url": "https://files.pythonhosted.org/packages/5b/7b/f86d8453d75245b6b19ec63f69f8aeb3bd69565845760cbdae8a04b97a78/pyrail-0.4.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-28 00:42:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "tjorim",
"github_project": "pyrail",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "pyrail"
}