Skip to content

Commit 2180f49

Browse files
feat: new request listener
1 parent dfa84ae commit 2180f49

File tree

6 files changed

+75
-63
lines changed

6 files changed

+75
-63
lines changed

squarecloud/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from .client import Client, create_config_file
22
from .square import File
33
from .errors import *
4-
from .http.router import Endpoint
4+
from .http.endpoints import Endpoint

squarecloud/app.py

Lines changed: 49 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
from .data import AppData
22
from abc import ABC
3-
from typing import Literal, TYPE_CHECKING
3+
from typing import Literal, TYPE_CHECKING, Callable
44
from .square import File
55
from .data import StatusData, LogsData, FullLogsData, BackupData
6-
from .http import Response
6+
from .http import Response, HTTPClient, Endpoint
77
from .errors import SquareException
8+
from .listener import ListenerManager
89

910
# avoid circular imports
1011
if TYPE_CHECKING:
@@ -57,103 +58,111 @@ class Application(AbstractApplication):
5758
# nine arguments is available in this case
5859
# pylint: disable=invalid-name
5960
__slots__ = [
60-
'__client',
61-
'__http',
62-
'__id',
63-
'__tag',
64-
'__ram',
65-
'__lang',
66-
'__type',
67-
'__cluster',
68-
'__is_website',
69-
'__avatar',
61+
'_client',
62+
'_http',
63+
'_listener',
64+
'_data',
7065
'cache'
7166
]
7267

73-
def __init__(self, client: 'Client', data: AppData):
74-
self.__client: Client = client
75-
self.__id: str = data.id
76-
self.__tag: str = data.tag
77-
self.__ram: int = data.ram
78-
self.__lang: Literal['javascript', 'typescript', 'python'] = data.lang
79-
self.__type: Literal['free', 'paid'] = data.type
80-
self.__cluster: str = data.cluster
81-
self.__is_website: bool = data.isWebsite
82-
self.__avatar: str = data.avatar
68+
def __init__(self, client: 'Client', http: HTTPClient, data: AppData):
69+
self._client: 'Client' = client
70+
self._http = http
71+
self._listener: ListenerManager = ListenerManager(self)
72+
self._data = data
8373
self.cache: AppCache = AppCache()
8474

8575
def __repr__(self):
8676
return f'<{self.__class__.__name__} tag={self.tag} id={self.id}>'
8777

78+
@property
79+
def data(self):
80+
return self._data
81+
8882
@property
8983
def client(self):
9084
"""client instance"""
91-
return self.__client
85+
return self._client
9286

9387
@property
9488
def id(self):
9589
"""application's id"""
96-
return self.__id
90+
return self.data.id
9791

9892
@property
9993
def tag(self):
10094
"""application's tag"""
101-
return self.__tag
95+
return self.data.tag
10296

10397
@property
10498
def ram(self):
10599
"""application's allocated ram"""
106-
return self.__ram
100+
return self.data.ram
107101

108102
@property
109103
def lang(self):
110104
"""application's programing language"""
111-
return self.__lang
105+
return self.data.lang
112106

113107
@property
114108
def type(self):
115109
"""application's type"""
116-
return self.__type
110+
return self.data.type
117111

118112
@property
119113
def cluster(self):
120114
"""application's cluster"""
121-
return self.__cluster
115+
return self.data.cluster
122116

123117
@property
124118
def is_website(self):
125119
"""whether the application is a website"""
126-
return self.__is_website
120+
return self.data.isWebsite
127121

128122
@property
129123
def avatar(self):
130124
"""application's avatar"""
131-
return self.__avatar
125+
return self.data.avatar
126+
127+
def on_request(self, endpoint: Endpoint) -> Callable:
128+
def wrapper(func):
129+
self._listener.add_listener(endpoint, func)
130+
131+
return wrapper
132132

133133
async def logs(self, update_cache: bool = True) -> LogsData:
134134
"""get application's logs"""
135-
logs: LogsData = await self.__client.get_logs(self.id)
135+
logs: LogsData = await self.client.get_logs(self.id)
136+
endpoint: Endpoint = Endpoint.logs()
137+
await self._listener.on_request_end(endpoint=endpoint, logs=logs)
136138
if update_cache:
137139
self.cache.logs = logs
138140
return logs
139141

140142
async def full_logs(self, update_cache: bool = True) -> FullLogsData:
141143
"""get application's full logs"""
142-
full_logs: FullLogsData = await self.__client.logs_complete(self.id)
144+
full_logs: FullLogsData = await self.client.full_logs(self.id)
145+
endpoint: Endpoint = Endpoint.full_logs()
146+
await self._listener.on_request_end(
147+
endpoint=endpoint, full_logs=full_logs)
143148
if update_cache:
144149
self.cache.full_logs = full_logs
145150
return full_logs
146151

147152
async def status(self, update_cache: bool = True) -> StatusData:
148153
"""get application's status"""
149-
status: StatusData = await self.__client.app_status(self.id)
154+
status: StatusData = await self.client.app_status(self.id)
155+
endpoint: Endpoint = Endpoint.app_status()
156+
await self._listener.on_request_end(endpoint=endpoint, status=status)
150157
if update_cache:
151158
self.cache.status = status
152159
return status
153160

154161
async def backup(self, update_cache: bool = True) -> BackupData:
155162
"""make backup of this application"""
156-
backup: BackupData = await self.__client.backup(self.id)
163+
backup: BackupData = await self.client.backup(self.id)
164+
endpoint: Endpoint = Endpoint.backup()
165+
await self._listener.on_request_end(endpoint=endpoint, backup=backup)
157166
if update_cache:
158167
self.cache.backup = backup
159168
return backup
@@ -162,26 +171,26 @@ async def start(self, update_cache: bool = True) -> Response:
162171
"""start the application"""
163172
if update_cache:
164173
self.cache.status.running = True
165-
return await self.__client.start_app(self.id)
174+
return await self.client.start_app(self.id)
166175

167176
async def stop(self, update_cache: bool = True) -> Response:
168177
"""stop the application"""
169-
result = await self.__client.stop_app(self.id)
178+
result = await self.client.stop_app(self.id)
170179
if update_cache:
171180
self.cache.status.running = False
172181
return result
173182

174183
async def restart(self, update_cache: bool = True) -> Response:
175184
"""restart the application"""
176-
result = await self.__client.restart_app(self.id)
185+
result = await self.client.restart_app(self.id)
177186
if update_cache:
178187
self.cache.status.status = 'restarting'
179188
return result
180189

181190
async def delete(self) -> Response:
182191
"""delete the application"""
183-
return await self.__client.delete_app(self.id)
192+
return await self.client.delete_app(self.id)
184193

185194
async def commit(self, file: File) -> Response:
186195
"""commit the application"""
187-
return await self.__client.commit(self.id, file=file)
196+
return await self.client.commit(self.id, file=file)

squarecloud/client.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""This module is a wrapper for using the SquareCloud API"""
22
from __future__ import annotations
33

4-
import asyncio
54
import logging
65
from abc import ABC, abstractmethod
76
from typing import List, Literal, Any, Callable
87

8+
from .app import Application
99
from .data import (
1010
AppData,
1111
StatusData,
@@ -15,12 +15,11 @@
1515
FullLogsData,
1616
UploadData
1717
)
18+
from .errors import ApplicationNotFound, InvalidFile
1819
from .http import HTTPClient, Response
19-
from .http.router import Endpoint
20+
from .http.endpoints import Endpoint
2021
from .logs import logger
2122
from .square import File
22-
from .app import Application
23-
from .errors import ApplicationNotFound, InvalidFile
2423
from .types import (
2524
UserPayload,
2625
StatusPayload,
@@ -144,7 +143,7 @@ async def get_logs(self, app_id: str) -> LogsData:
144143
logs_data: LogsData = LogsData(**payload)
145144
return logs_data
146145

147-
async def logs_complete(self, app_id: str) -> FullLogsData:
146+
async def full_logs(self, app_id: str) -> FullLogsData:
148147
"""
149148
Get logs for an application'
150149
@@ -249,7 +248,8 @@ async def app(self, app_id: str) -> Application:
249248
raise ApplicationNotFound
250249
app_data = app_data.pop()
251250
app: Application = Application(
252-
client=self, data=AppData(**app_data)) # type: ignore
251+
client=self, http=self._http,
252+
data=AppData(**app_data)) # type: ignore
253253
return app
254254

255255
async def all_apps(self) -> List[Application]:
@@ -264,8 +264,9 @@ async def all_apps(self) -> List[Application]:
264264
apps_data: List[AppData] = [
265265
AppData(**app_data) for app_data in # type: ignore
266266
payload['applications']]
267-
apps: List[Application] = [Application(client=self, data=data) for data
268-
in apps_data]
267+
apps: List[Application] = [
268+
Application(client=self, http=self._http, data=data) for data
269+
in apps_data]
269270
return apps
270271

271272
async def upload_app(self, file: File) -> UploadData:

squarecloud/http/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
from .http_client import HTTPClient, Response
2+
from .endpoints import Endpoint

squarecloud/http/router.py renamed to squarecloud/http/endpoints.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ def __init__(self, name: str):
2525
self.method: str = endpoint['METHOD']
2626
self.path: str = endpoint['PATH']
2727

28+
def __eq__(self, other: Endpoint):
29+
return isinstance(other, Endpoint) and self.name == other.name
30+
2831
def __repr__(self):
2932
return f"<{self.__class__.__name__}('{self.name}')>"
3033

squarecloud/http/http_client.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
from __future__ import annotations
22

3+
34
import aiohttp
45

5-
from .router import Endpoint, Router
6+
from .endpoints import Endpoint, Router
67
from ..errors import (
78
NotFoundError,
89
RequestError,
910
BadRequestError,
1011
AuthenticationFailure
1112
)
13+
from typing import Any, Literal
1214
from ..logs import logger
1315
from ..square import File
14-
1516
from ..types import RawResponseData
1617

1718

@@ -20,13 +21,13 @@ class Response:
2021

2122
def __init__(self, data: RawResponseData, route) -> None:
2223
self.data = data
23-
self.route = route
24-
self.headers = data.get('headers')
25-
self.status = data.get('status')
26-
self.code = data.get('code')
27-
self.message = data.get('message')
28-
self.response = data.get('response')
29-
self.app = data.get('app')
24+
self.route: Router = route
25+
self.headers: dict[str, Any] = data.get('headers')
26+
self.status: Literal['success', 'error'] = data.get('status')
27+
self.code: int = data.get('code')
28+
self.message: str = data.get('message')
29+
self.response: dict[str, Any] = data.get('response')
30+
self.app: dict[str, Any] = data.get('app')
3031

3132

3233
class HTTPClient:
@@ -35,7 +36,6 @@ class HTTPClient:
3536
def __init__(self, api_key: str) -> None:
3637
self.api_key = api_key
3738
self.__session = aiohttp.ClientSession
38-
self.trace_config: aiohttp.TraceConfig = aiohttp.TraceConfig()
3939

4040
async def request(self, route: Router, **kwargs) -> Response:
4141
"""
@@ -50,15 +50,13 @@ async def request(self, route: Router, **kwargs) -> Response:
5050

5151
if route.method == 'POST':
5252
kwargs['skip_auto_headers'] = {'Content-Type'}
53-
if route.endpoint.name in ('COMMIT', 'UPLOAD'):
53+
if route.endpoint in (Endpoint.commit(), Endpoint.upload()):
5454
del kwargs['skip_auto_headers']
5555
file = kwargs.pop('file')
5656
form = aiohttp.FormData()
5757
form.add_field('file', file.bytes, filename=file.name)
5858
kwargs['data'] = form
59-
60-
async with self.__session(
61-
headers=headers, trace_configs=[self.trace_config]) as session:
59+
async with self.__session(headers=headers) as session:
6260
async with session.request(url=route.url, method=route.method,
6361
**kwargs) as resp:
6462
status_code = resp.status

0 commit comments

Comments
 (0)