Skip to content

Commit

Permalink
Add aiolimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
Bre77 committed Mar 5, 2024
1 parent 4e18915 commit cf42f5f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 28 deletions.
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
aiohttp==3.*
aiohttp==3.*
aiolimiter=1.*
58 changes: 31 additions & 27 deletions tesla_fleet_api/teslafleetapi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import aiohttp
from aiolimiter import AsyncLimiter

from json import dumps
from .exceptions import raise_for_status, InvalidRegion, LibraryError, InvalidToken
from typing import Any
Expand All @@ -9,6 +11,7 @@
from .user import User
from .vehicle import Vehicle

rate_limit = AsyncLimiter(5, 10)

# Based on https://developer.tesla.com/docs/fleet-api
class TeslaFleetApi:
Expand Down Expand Up @@ -93,35 +96,36 @@ async def _request(
json = {k: v for k, v in json.items() if v is not None}
LOGGER.debug("Body: %s", dumps(json))

async with self.session.request(
method,
f"{self.server}/{path}",
headers={
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json",
},
json=json,
params=params,
) as resp:
LOGGER.debug("Response Status: %s", resp.status)
if self.raise_for_status and not resp.ok:
await raise_for_status(resp)
elif resp.status == 401 and resp.content_type != "application/json":
# Manufacture a response since Tesla doesn't provide a body for token expiration.
return {
"response": None,
"error": InvalidToken.key,
"error_message": "The OAuth token has expired.",
}
if resp.content_type == "application/json":
data = await resp.json()
LOGGER.debug("Response JSON: %s", data)
async with rate_limit:
async with self.session.request(
method,
f"{self.server}/{path}",
headers={
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json",
},
json=json,
params=params,
) as resp:
LOGGER.debug("Response Status: %s", resp.status)
if self.raise_for_status and not resp.ok:
await raise_for_status(resp)
elif resp.status == 401 and resp.content_type != "application/json":
# Manufacture a response since Tesla doesn't provide a body for token expiration.
return {
"response": None,
"error": InvalidToken.key,
"error_message": "The OAuth token has expired.",
}
if resp.content_type == "application/json":
data = await resp.json()
LOGGER.debug("Response JSON: %s", data)
return data

data = await resp.text()
LOGGER.debug("Response Text: %s", data)
return data

data = await resp.text()
LOGGER.debug("Response Text: %s", data)
return data

async def status(self):
"""This endpoint returns the string "ok" if the API is operating normally. No HTTP headers are required."""
if not self.server:
Expand Down

0 comments on commit cf42f5f

Please sign in to comment.