-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding Mapbox provider #8
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
76 changes: 76 additions & 0 deletions
76
src/traveltime_google_comparison/requests/mapbox_handler.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import logging | ||
from datetime import datetime | ||
|
||
import aiohttp | ||
from aiolimiter import AsyncLimiter | ||
from traveltimepy import Coordinates | ||
|
||
from traveltime_google_comparison.config import Mode | ||
from traveltime_google_comparison.requests.base_handler import ( | ||
BaseRequestHandler, | ||
RequestResult, | ||
) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class MapboxApiError(Exception): | ||
pass | ||
|
||
|
||
class MapboxRequestHandler(BaseRequestHandler): | ||
MAPBOX_ROUTES_URL = "https://api.mapbox.com/directions/v5/mapbox" | ||
|
||
default_timeout = aiohttp.ClientTimeout(total=60) | ||
|
||
def __init__(self, api_key, max_rpm): | ||
self.api_key = api_key | ||
self._rate_limiter = AsyncLimiter(max_rpm // 60, 1) | ||
|
||
async def send_request( | ||
self, | ||
origin: Coordinates, | ||
destination: Coordinates, | ||
departure_time: datetime, | ||
mode: Mode = Mode.DRIVING, | ||
) -> RequestResult: | ||
route = f"{origin.lng},{origin.lat};{destination.lng},{destination.lat}" # for Mapbox lat/lng are flipped! | ||
transport_mode = get_mapbox_specific_mode(mode) | ||
params = { | ||
"depart_at": departure_time.strftime("%Y-%m-%dT%H:%M:%SZ"), | ||
"access_token": self.api_key, | ||
"exclude": "ferry", # by default I think it includes ferries, but for our API we use just driving, without ferries | ||
} | ||
try: | ||
async with aiohttp.ClientSession( | ||
timeout=self.default_timeout | ||
) as session, session.get( | ||
f"{self.MAPBOX_ROUTES_URL}/{transport_mode}/{route}", params=params | ||
) as response: | ||
data = await response.json() | ||
code = data["code"] | ||
if code == "Ok": | ||
duration = data["routes"][0]["duration"] | ||
if not duration: | ||
raise MapboxApiError( | ||
"No route found between origin and destination." | ||
) | ||
return RequestResult(travel_time=int(duration)) | ||
else: | ||
error_message = data.get("detailedError", "") | ||
logger.error( | ||
f"Error in Mapbox API response: {response.status} - {error_message}" | ||
) | ||
return RequestResult(None) | ||
except Exception as e: | ||
logger.error(f"Exception during requesting Mapbox API, {e}") | ||
return RequestResult(None) | ||
|
||
|
||
def get_mapbox_specific_mode(mode: Mode) -> str: | ||
if mode == Mode.DRIVING: | ||
return "driving-traffic" | ||
elif mode == Mode.PUBLIC_TRANSPORT: | ||
raise ValueError("Public transport is not supported for Mapbox requests") | ||
else: | ||
raise ValueError(f"Unsupported mode: `{mode.value}`") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PT is a bit problematic (not just with mapbox, but in general), skipping it for now
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we don't have an env var allowing the user to specify transport mode for now anyways