Add caching to db ship api calls
This commit is contained in:
parent
f29f2b3cfa
commit
73d6cefa19
1 changed files with 14 additions and 6 deletions
|
@ -1,6 +1,7 @@
|
|||
"""JARVIS dbrand cog."""
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import aiohttp
|
||||
from naff import Client, Extension, InteractionContext
|
||||
|
@ -116,14 +117,15 @@ class DbrandCog(Extension):
|
|||
search = matches[0]
|
||||
dest = search.lower()
|
||||
data = self.cache.get(dest, None)
|
||||
if not data:
|
||||
if not data or data["cache_expiry"] < datetime.utcnow():
|
||||
api_link = self.api_url + dest
|
||||
data = await self._session.get(api_link)
|
||||
if 200 <= data.status < 400:
|
||||
data = await data.json()
|
||||
data["cache_expiry"] = datetime.utcnow() + timedelta(hours=24)
|
||||
self.cache[dest] = data
|
||||
else:
|
||||
data = None
|
||||
self.cache[dest] = data
|
||||
fields = None
|
||||
if data is not None and data["is_valid"] and data["shipping_available"]:
|
||||
fields = []
|
||||
|
@ -131,10 +133,16 @@ class DbrandCog(Extension):
|
|||
EmbedField(data["carrier"] + " " + data["tier-title"], data["time-title"])
|
||||
)
|
||||
for service in data["shipping_services_available"][1:]:
|
||||
service_data = await self._session.get(self.api_url + dest + "/" + service["url"])
|
||||
service_data = self.cache.get(f"{dest}-{service}")
|
||||
if not service_data or service_data["cache_expiry"] < datetime.utcnow():
|
||||
service_data = await self._session.get(
|
||||
self.api_url + dest + "/" + service["url"]
|
||||
)
|
||||
if service_data.status > 400:
|
||||
continue
|
||||
service_data = await service_data.json()
|
||||
service_data["cache_expiry"] = datetime.utcnow() + timedelta(hours=24)
|
||||
self.cache[f"{dest}-{service}"] = service_data
|
||||
fields.append(
|
||||
EmbedField(
|
||||
service_data["carrier"] + " " + service_data["tier-title"],
|
||||
|
|
Loading…
Add table
Reference in a new issue