Refactored
This commit is contained in:
parent
7a2948570b
commit
e7248723f5
5 changed files with 164 additions and 107 deletions
|
|
@ -1,5 +1,3 @@
|
|||
import asyncio
|
||||
import atexit
|
||||
from re import compile
|
||||
from typing import Any, Callable
|
||||
|
||||
|
|
@ -11,35 +9,32 @@ class Minecraft:
|
|||
self.host = host.rstrip("/")
|
||||
self.port = port
|
||||
self.headers = {"Authorization": password}
|
||||
self.session = ClientSession()
|
||||
atexit.register(self.exit)
|
||||
self._hooks: list[Callable] = []
|
||||
|
||||
def exit(self):
|
||||
asyncio.run(self.session.close())
|
||||
|
||||
async def _get(self, method: str, **json: Any):
|
||||
async with self.session.get(
|
||||
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
return await response.json()
|
||||
raise ConnectionError(
|
||||
f"Error while sending {method} to Server: HTTP code {response.status}."
|
||||
)
|
||||
|
||||
async def _stream(self, method: str, **json: Any):
|
||||
async with self.session.get(
|
||||
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
async for chunk, _ in response.content.iter_chunks():
|
||||
yield chunk
|
||||
else:
|
||||
async with ClientSession() as session:
|
||||
async with session.get(
|
||||
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
return await response.json()
|
||||
raise ConnectionError(
|
||||
f"Error while sending {method} to Server: HTTP code {response.status}."
|
||||
)
|
||||
|
||||
async def _stream(self, method: str, **json: Any):
|
||||
async with ClientSession() as session:
|
||||
async with session.get(
|
||||
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
async for chunk, _ in response.content.iter_chunks():
|
||||
yield chunk
|
||||
else:
|
||||
raise ConnectionError(
|
||||
f"Error while sending {method} to Server: HTTP code {response.status}."
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
return await self._get("/start")
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue