Skip to content

Commit 19b0916

Browse files
committed
Fix typing: Replace Dict->dict, List->list
1 parent 1b278e0 commit 19b0916

File tree

4 files changed

+31
-41
lines changed

4 files changed

+31
-41
lines changed

examples/example_fastapi/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from datetime import datetime
88
from os import listdir
99
from pathlib import Path
10-
from typing import Dict, Optional
10+
from typing import Optional
1111

1212
import aiohttp
1313
from fastapi import FastAPI
@@ -84,7 +84,7 @@ async def check_lifespan():
8484

8585

8686
@app.get("/environ")
87-
async def environ() -> Dict[str, str]:
87+
async def environ() -> dict[str, str]:
8888
"""List environment variables"""
8989
return dict(os.environ)
9090

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

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,24 +18,14 @@
1818
import subprocess
1919
import sys
2020
import traceback
21+
from collections.abc import AsyncIterable
2122
from contextlib import redirect_stdout
2223
from dataclasses import dataclass, field
2324
from enum import Enum
2425
from io import StringIO
2526
from os import system
2627
from shutil import make_archive
27-
from typing import (
28-
Any,
29-
AsyncIterable,
30-
Dict,
31-
List,
32-
Literal,
33-
NewType,
34-
Optional,
35-
Tuple,
36-
Union,
37-
cast,
38-
)
28+
from typing import Any, Literal, NewType, Optional, Union, cast
3929

4030
import aiohttp
4131
import msgpack
@@ -80,15 +70,15 @@ class ConfigurationPayload:
8070
ipv6: Optional[str] = None
8171
route: Optional[str] = None
8272
ipv6_gateway: Optional[str] = None
83-
dns_servers: List[str] = field(default_factory=list)
84-
volumes: List[Volume] = field(default_factory=list)
85-
variables: Optional[Dict[str, str]] = None
86-
authorized_keys: Optional[List[str]] = None
73+
dns_servers: list[str] = field(default_factory=list)
74+
volumes: list[Volume] = field(default_factory=list)
75+
variables: Optional[dict[str, str]] = None
76+
authorized_keys: Optional[list[str]] = None
8777

8878

8979
@dataclass
9080
class RunCodePayload:
91-
scope: Dict
81+
scope: dict
9282

9383

9484
# Open a socket to receive instructions from the host
@@ -117,7 +107,7 @@ def setup_hostname(hostname: str):
117107
system(f"hostname {hostname}")
118108

119109

120-
def setup_variables(variables: Optional[Dict[str, str]]):
110+
def setup_variables(variables: Optional[dict[str, str]]):
121111
if variables is None:
122112
return
123113
for key, value in variables.items():
@@ -129,7 +119,7 @@ def setup_network(
129119
ipv6: Optional[str],
130120
ipv4_gateway: Optional[str],
131121
ipv6_gateway: Optional[str],
132-
dns_servers: Optional[List[str]] = None,
122+
dns_servers: Optional[list[str]] = None,
133123
):
134124
"""Setup the system with info from the host."""
135125
dns_servers = dns_servers or []
@@ -180,13 +170,13 @@ def setup_input_data(input_data: bytes):
180170
os.system("unzip -q /opt/input.zip -d /data")
181171

182172

183-
def setup_authorized_keys(authorized_keys: List[str]) -> None:
173+
def setup_authorized_keys(authorized_keys: list[str]) -> None:
184174
path = Path("/root/.ssh/authorized_keys")
185175
path.parent.mkdir(exist_ok=True)
186176
path.write_text("\n".join(key for key in authorized_keys))
187177

188178

189-
def setup_volumes(volumes: List[Volume]):
179+
def setup_volumes(volumes: list[Volume]):
190180
for volume in volumes:
191181
logger.debug(f"Mounting /dev/{volume.device} on {volume.mount}")
192182
os.makedirs(volume.mount, exist_ok=True)
@@ -213,7 +203,7 @@ async def receive():
213203
"type": f"lifespan.{event}",
214204
}
215205

216-
async def send(response: Dict):
206+
async def send(response: dict):
217207
response_type = response.get("type")
218208
if response_type == f"lifespan.{event}.complete":
219209
lifespan_completion.set()
@@ -260,7 +250,7 @@ async def setup_code_asgi(code: bytes, encoding: Encoding, entrypoint: str) -> A
260250
app = getattr(module, app_name)
261251
elif encoding == Encoding.plain:
262252
# Execute the code and extract the entrypoint
263-
locals: Dict[str, Any] = {}
253+
locals: dict[str, Any] = {}
264254
exec(code, globals(), locals)
265255
app = locals[entrypoint]
266256
else:
@@ -313,7 +303,7 @@ async def setup_code(
313303
raise ValueError("Invalid interface. This should never happen.")
314304

315305

316-
async def run_python_code_http(application: ASGIApplication, scope: dict) -> Tuple[Dict, Dict, str, Optional[bytes]]:
306+
async def run_python_code_http(application: ASGIApplication, scope: dict) -> tuple[dict, dict, str, Optional[bytes]]:
317307
logger.debug("Running code")
318308
with StringIO() as buf, redirect_stdout(buf):
319309
# Execute in the same process, saves ~20ms than a subprocess
@@ -335,14 +325,14 @@ async def send(dico):
335325
await application(scope, receive, send)
336326

337327
logger.debug("Waiting for headers")
338-
headers: Dict
328+
headers: dict
339329
if scope["type"] == "http":
340330
headers = await send_queue.get()
341331
else:
342332
headers = {}
343333

344334
logger.debug("Waiting for body")
345-
response_body: Dict = await send_queue.get()
335+
response_body: dict = await send_queue.get()
346336

347337
logger.debug("Waiting for buffer")
348338
output = buf.getvalue()
@@ -394,7 +384,7 @@ def show_loading():
394384
return headers, body
395385

396386

397-
async def run_executable_http(scope: dict) -> Tuple[Dict, Dict, str, Optional[bytes]]:
387+
async def run_executable_http(scope: dict) -> tuple[dict, dict, str, Optional[bytes]]:
398388
logger.debug("Calling localhost")
399389

400390
tries = 0
@@ -453,8 +443,8 @@ async def process_instruction(
453443

454444
output: Optional[str] = None
455445
try:
456-
headers: Dict
457-
body: Dict
446+
headers: dict
447+
body: dict
458448
output_data: Optional[bytes]
459449

460450
if interface == Interface.asgi:
@@ -532,7 +522,7 @@ def setup_system(config: ConfigurationPayload):
532522
logger.debug("Setup finished")
533523

534524

535-
def umount_volumes(volumes: List[Volume]):
525+
def umount_volumes(volumes: list[Volume]):
536526
"Umount user related filesystems"
537527
system("sync")
538528
for volume in volumes:

tests/supervisor/test_jwk.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
# Avoid failures linked to settings when initializing the global VmPool object
88
os.environ["ALEPH_VM_ALLOW_VM_NETWORKING"] = "False"
99

10-
from typing import Any, Dict
10+
from typing import Any
1111

1212
import pytest
1313

@@ -23,15 +23,15 @@ def valid_jwk_headers(mocker):
2323

2424
@pytest.mark.skip(reason="TODO: Fix this test")
2525
@pytest.mark.asyncio
26-
async def test_valid_signature(valid_jwk_headers: Dict[str, Any], mocker):
26+
async def test_valid_signature(valid_jwk_headers: dict[str, Any], mocker):
2727
request = mocker.AsyncMock()
2828
request.headers = valid_jwk_headers
2929
await authenticate_jwk(request)
3030

3131

3232
@pytest.mark.skip(reason="TODO: Fix this test")
3333
@pytest.mark.asyncio
34-
async def test_invalid_signature(valid_jwk_headers: Dict[str, Any], mocker):
34+
async def test_invalid_signature(valid_jwk_headers: dict[str, Any], mocker):
3535
valid_jwk_headers["X-SignedOperation"] = (
3636
'{"time":"2023-07-14T22:14:14.132Z","signature":"96ffdbbd1704d5f6bfe4698235a0de0d2f58668deaa4371422bee26664f313f51fd483c78c34c6b317fc209779f9ddd9c45accf558e3bf881b49ad970ebf0ade"}'
3737
)
@@ -44,7 +44,7 @@ async def test_invalid_signature(valid_jwk_headers: Dict[str, Any], mocker):
4444

4545
@pytest.mark.skip(reason="TODO: Fix this test")
4646
@pytest.mark.asyncio
47-
async def test_expired_token(valid_jwk_headers: Dict[str, Any], mocker):
47+
async def test_expired_token(valid_jwk_headers: dict[str, Any], mocker):
4848
mocker.patch("aleph.vm.orchestrator.views.authentication.is_token_still_valid", lambda timestamp: False)
4949
request = mocker.AsyncMock()
5050
request.headers = valid_jwk_headers
@@ -55,7 +55,7 @@ async def test_expired_token(valid_jwk_headers: Dict[str, Any], mocker):
5555

5656
@pytest.mark.parametrize("missing_header", ["X-SignedPubKey", "X-SignedOperation"])
5757
@pytest.mark.asyncio
58-
async def test_missing_headers(valid_jwk_headers: Dict[str, Any], mocker, missing_header: str):
58+
async def test_missing_headers(valid_jwk_headers: dict[str, Any], mocker, missing_header: str):
5959
del valid_jwk_headers[missing_header]
6060

6161
request = mocker.AsyncMock()

vm_connector/main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import json
22
import logging
3-
from typing import Dict, Optional, Union
3+
from typing import Optional
44

55
import aiohttp
66
from aleph_client.asynchronous import create_post
@@ -24,7 +24,7 @@ def read_root():
2424
return {"Server": "Aleph.im VM Connector"}
2525

2626

27-
async def get_latest_message_amend(ref: str, sender: str) -> Optional[Dict]:
27+
async def get_latest_message_amend(ref: str, sender: str) -> Optional[dict]:
2828
async with aiohttp.ClientSession() as session:
2929
url = (
3030
f"{settings.API_SERVER}/api/v0/messages.json?msgType=STORE&sort_order=-1" f"&refs={ref}&addresses={sender}"
@@ -38,7 +38,7 @@ async def get_latest_message_amend(ref: str, sender: str) -> Optional[Dict]:
3838
return None
3939

4040

41-
async def get_message(hash_: str) -> Optional[Dict]:
41+
async def get_message(hash_: str) -> Optional[dict]:
4242
async with aiohttp.ClientSession() as session:
4343
url = f"{settings.API_SERVER}/api/v0/messages.json?hashes={hash_}"
4444
resp = await session.get(url)
@@ -63,7 +63,7 @@ async def stream_url_chunks(url):
6363

6464

6565
@app.get("/download/message/{ref}")
66-
async def download_message(ref: str) -> Dict:
66+
async def download_message(ref: str) -> dict:
6767
"""
6868
Fetch on Aleph and return a VM function message, after checking its validity.
6969
Used by the VM Supervisor run the code.

0 commit comments

Comments
 (0)