44from typing import Any , Awaitable
55from os .path import exists
66import aiohttp
7+ import aiofiles
78
89# cryptography
9- from cryptography .hazmat .primitives .ciphers .aead import AESGCM
1010from cryptography .hazmat .primitives .asymmetric import ec
11- from cryptography .hazmat .primitives import hashes , serialization
11+ from cryptography .hazmat .primitives import serialization
1212from cryptography .hazmat .backends import default_backend
1313
1414from .exceptions import raise_for_status , InvalidRegion , LibraryError , ResponseError
@@ -30,7 +30,7 @@ class TeslaFleetApi:
3030 session : aiohttp .ClientSession
3131 headers : dict [str , str ]
3232 refresh_hook : Awaitable | None = None
33- _private_key : ec .EllipticCurvePrivateKey
33+ _private_key : ec .EllipticCurvePrivateKey | None = None
3434
3535 def __init__ (
3636 self ,
@@ -161,8 +161,8 @@ async def products(self) -> dict[str, Any]:
161161 "api/1/products" ,
162162 )
163163
164- def private_key (self , path : str = "private_key.pem" ) -> ec .EllipticCurvePrivateKey :
165- """Create or load the private key."""
164+ async def get_private_key (self , path : str = "private_key.pem" ) -> ec .EllipticCurvePrivateKey :
165+ """Get or create the private key."""
166166 if not exists (path ):
167167 self ._private_key = ec .generate_private_key (
168168 ec .SECP256R1 (), default_backend ()
@@ -173,16 +173,15 @@ def private_key(self, path: str = "private_key.pem") -> ec.EllipticCurvePrivateK
173173 format = serialization .PrivateFormat .TraditionalOpenSSL ,
174174 encryption_algorithm = serialization .NoEncryption (),
175175 )
176- with open (path , "wb" ) as key_file :
177- key_file .write (pem )
178- return self ._private_key
176+ async with aiofiles .open (path , "wb" ) as key_file :
177+ await key_file .write (pem )
179178 else :
180179 try :
181- with open (path , "rb" ) as key_file :
182- key_data = key_file .read ()
183- value = serialization .load_pem_private_key (
184- key_data , password = None , backend = default_backend ()
185- )
180+ async with aiofiles . open (path , "rb" ) as key_file :
181+ key_data = await key_file .read ()
182+ value = serialization .load_pem_private_key (
183+ key_data , password = None , backend = default_backend ()
184+ )
186185 except FileNotFoundError :
187186 raise FileNotFoundError (f"Private key file not found at { path } " )
188187 except PermissionError :
@@ -191,4 +190,4 @@ def private_key(self, path: str = "private_key.pem") -> ec.EllipticCurvePrivateK
191190 if not isinstance (value , ec .EllipticCurvePrivateKey ):
192191 raise AssertionError ("Loaded key is not an EllipticCurvePrivateKey" )
193192 self ._private_key = value
194- return self ._private_key
193+ return self ._private_key
0 commit comments