Minor optimizations with asyncio
This commit is contained in:
parent
ac6434893d
commit
b0ed384ba3
2 changed files with 10 additions and 8 deletions
14
src/main.py
14
src/main.py
|
|
@ -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
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import docker
|
||||
from docker import DockerClient
|
||||
from docker.models.containers import Container
|
||||
|
|
@ -25,7 +27,7 @@ app.add_middleware(
|
|||
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
|
||||
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 = list(filter(lambda x: x is not None, ret))
|
||||
return [x.asdict() for x in ret]
|
||||
ret = await asyncio.gather(*(Server.from_container(c) for c in containers))
|
||||
ret = await asyncio.gather(*(x.asdict() for x in ret))
|
||||
return ret
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index(response: Response, all: bool = False, sort: str = ""):
|
||||
async def index(response: Response, all: bool = False, sort: str = ""):
|
||||
try:
|
||||
data = list_servers(client, all=all)
|
||||
data = await list_servers(client, all=all)
|
||||
if sort:
|
||||
data = sorted(data, key=lambda x: x[sort])
|
||||
response.status_code = status.HTTP_200_OK
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ class Server:
|
|||
self.online_players: int = params.online_players
|
||||
self.players: list[JavaStatusPlayer] = params.players
|
||||
|
||||
def asdict(self) -> dict:
|
||||
async def asdict(self) -> dict:
|
||||
d = self.__dict__
|
||||
d["players"] = [x.__dict__ for x in self.players]
|
||||
return d
|
||||
|
|
@ -114,7 +114,7 @@ class Server:
|
|||
return []
|
||||
|
||||
@staticmethod
|
||||
def from_container(container: Container):
|
||||
async def from_container(container: Container):
|
||||
"""Attempts to build out a server instance from a given container
|
||||
|
||||
Args:
|
||||
|
|
|
|||
Loading…
Reference in a new issue