Minor optimizations with asyncio

This commit is contained in:
oitsjustjose 2026-08-28 22:12:47 -05:00
commit b0ed384ba3
2 changed files with 10 additions and 8 deletions

View file

@ -5,6 +5,8 @@ Description: A Flask API service for the running Minecraft server statuses
Run via Docker with either network mode = HOST, **OR** set the environment variable HOST_IP to the IP of your server Run via Docker with either network mode = HOST, **OR** set the environment variable HOST_IP to the IP of your server
""" """
import asyncio
import docker import docker
from docker import DockerClient from docker import DockerClient
from docker.models.containers import Container from docker.models.containers import Container
@ -25,7 +27,7 @@ app.add_middleware(
client = docker.from_env() client = docker.from_env()
def list_servers(client: DockerClient, all: bool = False) -> list[dict]: async def list_servers(client: DockerClient, all: bool = False) -> list[dict]:
""" """
Distills the container data for all servers on the current host into a usable format Distills the container data for all servers on the current host into a usable format
Arguments: Arguments:
@ -41,15 +43,15 @@ def list_servers(client: DockerClient, all: bool = False) -> list[dict]:
) )
) )
ret = [Server.from_container(c) for c in containers] ret = await asyncio.gather(*(Server.from_container(c) for c in containers))
ret = list(filter(lambda x: x is not None, ret)) ret = await asyncio.gather(*(x.asdict() for x in ret))
return [x.asdict() for x in ret] return ret
@app.get("/") @app.get("/")
def index(response: Response, all: bool = False, sort: str = ""): async def index(response: Response, all: bool = False, sort: str = ""):
try: try:
data = list_servers(client, all=all) data = await list_servers(client, all=all)
if sort: if sort:
data = sorted(data, key=lambda x: x[sort]) data = sorted(data, key=lambda x: x[sort])
response.status_code = status.HTTP_200_OK response.status_code = status.HTTP_200_OK

View file

@ -59,7 +59,7 @@ class Server:
self.online_players: int = params.online_players self.online_players: int = params.online_players
self.players: list[JavaStatusPlayer] = params.players self.players: list[JavaStatusPlayer] = params.players
def asdict(self) -> dict: async def asdict(self) -> dict:
d = self.__dict__ d = self.__dict__
d["players"] = [x.__dict__ for x in self.players] d["players"] = [x.__dict__ for x in self.players]
return d return d
@ -114,7 +114,7 @@ class Server:
return [] return []
@staticmethod @staticmethod
def from_container(container: Container): async def from_container(container: Container):
"""Attempts to build out a server instance from a given container """Attempts to build out a server instance from a given container
Args: Args: