Skip to content

Commit 4ae14ce

Browse files
committed
hatch fmt on examples and tests/
1 parent 7060a90 commit 4ae14ce

File tree

5 files changed

+29
-37
lines changed

5 files changed

+29
-37
lines changed

examples/example_fastapi/main.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from datetime import datetime, timezone
99
from os import listdir
1010
from pathlib import Path
11-
from typing import Any, Optional
11+
from typing import Any
1212

1313
import aiohttp
1414
from aleph_message.models import (
@@ -128,8 +128,8 @@ async def read_aleph_messages() -> dict[str, MessagesResponse]:
128128
async def resolve_dns_hostname():
129129
"""Check if DNS resolution is working."""
130130
hostname = "example.org"
131-
ipv4: Optional[str] = None
132-
ipv6: Optional[str] = None
131+
ipv4: str | None = None
132+
ipv6: str | None = None
133133

134134
info = socket.getaddrinfo(hostname, 80, proto=socket.IPPROTO_TCP)
135135
if not info:
@@ -170,7 +170,7 @@ async def connect_ipv4():
170170
sock.settimeout(5)
171171
sock.connect((ipv4_host, 53))
172172
return {"result": True}
173-
except socket.timeout:
173+
except TimeoutError:
174174
logger.warning(f"Socket connection for host {ipv4_host} failed")
175175
return {"result": False}
176176

examples/example_fastapi_1.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from typing import Optional
2-
31
from fastapi import FastAPI
42

53
app = FastAPI()
@@ -11,10 +9,10 @@ def read_root():
119

1210

1311
@app.get("/run/{item_id}")
14-
def read_item(item_id: str, q: Optional[str] = None):
12+
def read_item(item_id: str, q: str | None = None):
1513
return {"item_id": item_id, "q": q}
1614

1715

1816
@app.post("/run/{item_id}")
19-
def read_item_post(item_id: str, q: Optional[str] = None):
17+
def read_item_post(item_id: str, q: str | None = None):
2018
return {"item_id_post": item_id, "q": q}

runtimes/aleph-debian-12-python/init1.py

+21-25
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,11 @@
1919
import sys
2020
import traceback
2121
from collections.abc import AsyncIterable
22-
from contextlib import redirect_stdout
2322
from dataclasses import dataclass, field
2423
from enum import Enum
25-
from io import StringIO
2624
from os import system
2725
from shutil import make_archive
28-
from typing import Any, Literal, NewType, Optional, Union, cast
26+
from typing import Any, Literal, NewType, cast
2927

3028
import aiohttp
3129
import msgpack
@@ -66,14 +64,14 @@ class ConfigurationPayload:
6664
code: bytes
6765
encoding: Encoding
6866
entrypoint: str
69-
ip: Optional[str] = None
70-
ipv6: Optional[str] = None
71-
route: Optional[str] = None
72-
ipv6_gateway: Optional[str] = None
67+
ip: str | None = None
68+
ipv6: str | None = None
69+
route: str | None = None
70+
ipv6_gateway: str | None = None
7371
dns_servers: list[str] = field(default_factory=list)
7472
volumes: list[Volume] = field(default_factory=list)
75-
variables: Optional[dict[str, str]] = None
76-
authorized_keys: Optional[list[str]] = None
73+
variables: dict[str, str] | None = None
74+
authorized_keys: list[str] | None = None
7775

7876

7977
@dataclass
@@ -107,19 +105,19 @@ def setup_hostname(hostname: str):
107105
system(f"hostname {hostname}")
108106

109107

110-
def setup_variables(variables: Optional[dict[str, str]]):
108+
def setup_variables(variables: dict[str, str] | None):
111109
if variables is None:
112110
return
113111
for key, value in variables.items():
114112
os.environ[key] = value
115113

116114

117115
def setup_network(
118-
ipv4: Optional[str],
119-
ipv6: Optional[str],
120-
ipv4_gateway: Optional[str],
121-
ipv6_gateway: Optional[str],
122-
dns_servers: Optional[list[str]] = None,
116+
ipv4: str | None,
117+
ipv6: str | None,
118+
ipv4_gateway: str | None,
119+
ipv6_gateway: str | None,
120+
dns_servers: list[str] | None = None,
123121
):
124122
"""Setup the system with info from the host."""
125123
dns_servers = dns_servers or []
@@ -188,9 +186,7 @@ def setup_volumes(volumes: list[Volume]):
188186
system("mount")
189187

190188

191-
async def wait_for_lifespan_event_completion(
192-
application: ASGIApplication, event: Union[Literal["startup", "shutdown"]]
193-
):
189+
async def wait_for_lifespan_event_completion(application: ASGIApplication, event: Literal["startup", "shutdown"]):
194190
"""
195191
Send the startup lifespan signal to the ASGI app.
196192
Specification: https://asgi.readthedocs.io/en/latest/specs/lifespan.html
@@ -295,7 +291,7 @@ async def setup_code(
295291
encoding: Encoding,
296292
entrypoint: str,
297293
interface: Interface,
298-
) -> Union[ASGIApplication, subprocess.Popen]:
294+
) -> ASGIApplication | subprocess.Popen:
299295
if interface == Interface.asgi:
300296
return await setup_code_asgi(code=code, encoding=encoding, entrypoint=entrypoint)
301297
elif interface == Interface.executable:
@@ -304,7 +300,7 @@ async def setup_code(
304300
raise ValueError("Invalid interface. This should never happen.")
305301

306302

307-
async def run_python_code_http(application: ASGIApplication, scope: dict) -> tuple[dict, dict, str, Optional[bytes]]:
303+
async def run_python_code_http(application: ASGIApplication, scope: dict) -> tuple[dict, dict, str, bytes | None]:
308304
logger.debug("Running code")
309305
# Execute in the same process, saves ~20ms than a subprocess
310306

@@ -386,7 +382,7 @@ def show_loading():
386382
return headers, body
387383

388384

389-
async def run_executable_http(scope: dict) -> tuple[dict, dict, str, Optional[bytes]]:
385+
async def run_executable_http(scope: dict) -> tuple[dict, dict, str, bytes | None]:
390386
logger.debug("Calling localhost")
391387

392388
tries = 0
@@ -413,7 +409,7 @@ async def run_executable_http(scope: dict) -> tuple[dict, dict, str, Optional[by
413409
async def process_instruction(
414410
instruction: bytes,
415411
interface: Interface,
416-
application: Union[ASGIApplication, subprocess.Popen],
412+
application: ASGIApplication | subprocess.Popen,
417413
) -> AsyncIterable[bytes]:
418414
if instruction == b"halt":
419415
logger.info("Received halt command")
@@ -443,11 +439,11 @@ async def process_instruction(
443439
logger.debug("msgpack.loads )")
444440
payload = RunCodePayload(**msg_)
445441

446-
output: Optional[str] = None
442+
output: str | None = None
447443
try:
448444
headers: dict
449445
body: dict
450-
output_data: Optional[bytes]
446+
output_data: bytes | None
451447

452448
if interface == Interface.asgi:
453449
application = cast(ASGIApplication, application)
@@ -540,7 +536,7 @@ async def main() -> None:
540536
setup_system(config)
541537

542538
try:
543-
app: Union[ASGIApplication, subprocess.Popen] = await setup_code(
539+
app: ASGIApplication | subprocess.Popen = await setup_code(
544540
config.code, config.encoding, config.entrypoint, config.interface
545541
)
546542
client.send(msgpack.dumps({"success": True}))

tests/supervisor/test_execution.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import json
32
import logging
43
from typing import Any
54

vm_connector/main.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import json
22
import logging
3-
from typing import Optional
43

54
import aiohttp
65
from aleph_client.asynchronous import create_post
@@ -24,7 +23,7 @@ def read_root():
2423
return {"Server": "Aleph.im VM Connector"}
2524

2625

27-
async def get_latest_message_amend(ref: str, sender: str) -> Optional[dict]:
26+
async def get_latest_message_amend(ref: str, sender: str) -> dict | None:
2827
async with aiohttp.ClientSession() as session:
2928
url = f"{settings.API_SERVER}/api/v0/messages.json?msgType=STORE&sort_order=-1&refs={ref}&addresses={sender}"
3029
resp = await session.get(url)
@@ -36,7 +35,7 @@ async def get_latest_message_amend(ref: str, sender: str) -> Optional[dict]:
3635
return None
3736

3837

39-
async def get_message(hash_: str) -> Optional[dict]:
38+
async def get_message(hash_: str) -> dict | None:
4039
async with aiohttp.ClientSession() as session:
4140
url = f"{settings.API_SERVER}/api/v0/messages.json?hashes={hash_}"
4241
resp = await session.get(url)

0 commit comments

Comments
 (0)