Skip to content

Commit

Permalink
Update README to enhance language selection and session management se… (
Browse files Browse the repository at this point in the history
  • Loading branch information
tjorim authored Jan 27, 2025
1 parent 549c131 commit 806e9ae
Show file tree
Hide file tree
Showing 2 changed files with 160 additions and 37 deletions.
191 changes: 156 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ An async Python wrapper for the iRail API, designed to make interacting with iRa
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.
Expand All @@ -15,13 +17,15 @@ pyRail is a Python library that provides a convenient interface for interacting
- 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
Expand All @@ -32,75 +36,192 @@ async def main():
# Sequential requests example
async with iRail() as api:
try:
async with iRail() as client:
# Get the total number of stations
stations = await api.get_stations()
if stations:
print(f"Total stations: {len(stations)}")
# Get the liveboard for a specific station
liveboard = await client.get_liveboard(station='Brussels-South')
if liveboard:
print(f"Liveboard for Brussels-South: {liveboard}")
# 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:
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}")
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())
```

## Configuration
You can configure the format and language for the API requests:
### 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
api = iRail(format='json', lang='en')
# 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)
```

- Supported formats: json, xml, jsonp
- Supported languages: nl, fr, en, de
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
```
```bash
git clone https://github.com/tjorim/pyrail.git
```
2. Open the project in a devcontainer:
```bash
```bash
cd pyrail
code .
```
Make sure you have the Remote - Containers extension installed in VS Code. The devcontainer setup includes all necessary dependencies and tools for development.
```
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
You can set the logging level at runtime to get detailed logs:

pyRail uses Python's built-in logging module. You can set the logging level at runtime to get detailed logs.

```python
import logging

api.set_logging_level(logging.DEBUG)
# Set the logging level to DEBUG
logging.basicConfig(level=logging.DEBUG)
```

## Contributing
Contributions are welcome! Please open an issue or submit a pull request.

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.
6 changes: 4 additions & 2 deletions pyrail/irail.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,10 @@ def _refill_tokens(self) -> None:

# Refill tokens, 3 tokens per second, cap tokens at 3
self.tokens = min(3, self.tokens + int(elapsed * 3))
# Refill burst tokens, 3 burst tokens per second, cap burst tokens at 5
self.burst_tokens = min(5, self.burst_tokens + int(elapsed * 3))

# Refill burst tokens only if the request rate is below 3 requests per second
if self.tokens == 3:
self.burst_tokens = min(5, self.burst_tokens + int(elapsed * 3))

async def _handle_rate_limit(self) -> None:
"""Handle rate limiting using a token bucket algorithm.
Expand Down

0 comments on commit 806e9ae

Please sign in to comment.