Cache API clients to reduce 500 risk(s)

This commit is contained in:
Reid 'arrdem' McKenzie 2023-06-19 23:24:10 -06:00
parent 10d827c39f
commit d5810a530f

View file

@ -8,6 +8,7 @@ Mostly related to monitoring and managing Printer state.
""" """
from contextlib import closing from contextlib import closing
from functools import cache
import logging import logging
from pathlib import Path from pathlib import Path
from pprint import pformat from pprint import pformat
@ -49,6 +50,11 @@ class OctoRest(_OR):
raise e raise e
@cache
def get_client(url, key):
return OctoRest(url=url, apikey=key)
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -65,7 +71,7 @@ def poll_printers(app: App, db: Db) -> None:
printer_job = {} printer_job = {}
try: try:
client = OctoRest(url=printer.url, apikey=printer.api_key) client = get_client(printer.url, printer.api_key)
printer_job: dict = client.job_info() printer_job: dict = client.job_info()
try: try:
printer_state: dict = client.printer().get("state").get("flags", {}) printer_state: dict = client.printer().get("state").get("flags", {})
@ -136,7 +142,7 @@ def push_jobs(app: App, db: Db) -> None:
db.delete_job(job.user_id, job.id) db.delete_job(job.user_id, job.id)
try: try:
client = OctoRest(url=printer.url, apikey=printer.api_key) client = get_client(printer.url, printer.api_key)
printer_job = client.job_info() printer_job = client.job_info()
try: try:
printer_state = client.printer().get("state").get("flags", {}) printer_state = client.printer().get("state").get("flags", {})
@ -182,7 +188,7 @@ def revoke_jobs(app: App, db: Db) -> None:
try: try:
log.info(f"Cancelling running job {job.id}") log.info(f"Cancelling running job {job.id}")
client = OctoRest(url=printer.url, apikey=printer.api_key) client = get_client(printer.url, printer.api_key)
try: try:
client.cancel() client.cancel()
except HTTPError as e: except HTTPError as e:
@ -211,7 +217,7 @@ def pull_jobs(app: App, db: Db) -> None:
for job in db.list_running_jobs(): for job in db.list_running_jobs():
printer = db.fetch_printer(pid=job.printer_id) printer = db.fetch_printer(pid=job.printer_id)
try: try:
client = OctoRest(url=printer.url, apikey=printer.api_key) client = get_client(printer.url, printer.api_key)
job_state = client.job_info() job_state = client.job_info()
try: try:
printer_state = client.printer().get("state").get("flags", {}) printer_state = client.printer().get("state").get("flags", {})