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."""
|
"""JARVIS dbrand cog."""
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
from naff import Client, Extension, InteractionContext
|
from naff import Client, Extension, InteractionContext
|
||||||
|
@ -116,14 +117,15 @@ class DbrandCog(Extension):
|
||||||
search = matches[0]
|
search = matches[0]
|
||||||
dest = search.lower()
|
dest = search.lower()
|
||||||
data = self.cache.get(dest, None)
|
data = self.cache.get(dest, None)
|
||||||
if not data:
|
if not data or data["cache_expiry"] < datetime.utcnow():
|
||||||
api_link = self.api_url + dest
|
api_link = self.api_url + dest
|
||||||
data = await self._session.get(api_link)
|
data = await self._session.get(api_link)
|
||||||
if 200 <= data.status < 400:
|
if 200 <= data.status < 400:
|
||||||
data = await data.json()
|
data = await data.json()
|
||||||
|
data["cache_expiry"] = datetime.utcnow() + timedelta(hours=24)
|
||||||
|
self.cache[dest] = data
|
||||||
else:
|
else:
|
||||||
data = None
|
data = None
|
||||||
self.cache[dest] = data
|
|
||||||
fields = None
|
fields = None
|
||||||
if data is not None and data["is_valid"] and data["shipping_available"]:
|
if data is not None and data["is_valid"] and data["shipping_available"]:
|
||||||
fields = []
|
fields = []
|
||||||
|
@ -131,10 +133,16 @@ class DbrandCog(Extension):
|
||||||
EmbedField(data["carrier"] + " " + data["tier-title"], data["time-title"])
|
EmbedField(data["carrier"] + " " + data["tier-title"], data["time-title"])
|
||||||
)
|
)
|
||||||
for service in data["shipping_services_available"][1:]:
|
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 service_data.status > 400:
|
if not service_data or service_data["cache_expiry"] < datetime.utcnow():
|
||||||
continue
|
service_data = await self._session.get(
|
||||||
service_data = await service_data.json()
|
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(
|
fields.append(
|
||||||
EmbedField(
|
EmbedField(
|
||||||
service_data["carrier"] + " " + service_data["tier-title"],
|
service_data["carrier"] + " " + service_data["tier-title"],
|
||||||
|
|
Loading…
Add table
Reference in a new issue