DataBridge¶
DataBridge is an entity that provides temporary data storage that exists within a single application session (from startup to exit). It is designed for data exchange between handlers.
The main way to access DataBridge is through DI.
1from argenta.di import FromDishka
2from argenta import DataBridge, Response
3
4# ... setting up router and other
5
6def my_handler(response: Response, data_bridge: FromDishka[DataBridge]):
7 # ... your code
Practical Example: Authentication
Let’s consider an example where the login command saves an authentication token, and the get-profile command uses it.
1from argenta import Router, Response, Command, DataBridge
2from argenta.command import Flag
3from argenta.di import FromDishka
4
5router = Router(title="Authentication")
6
7
8def authenticate_user(username: str) -> str:
9 return f"token_for_{username}"
10
11
12@router.command(Command("login", flags=Flag("username")))
13def login_handler(response: Response, data_bridge: FromDishka[DataBridge]):
14 username_flag = response.input_flags.get_flag_by_name("username")
15 if not username_flag or not username_flag.input_value:
16 print("Error: username must be specified using the --username flag.")
17 return
18
19 username = username_flag.input_value
20 token = authenticate_user(username)
21
22 data_bridge.update({"auth_token": token})
23 print(f"Login successful! User '{username}' authenticated.")
24
25
26@router.command("get-profile")
27def get_profile_handler(response: Response, data_bridge: FromDishka[DataBridge]):
28 token = data_bridge.get_by_key("auth_token")
29
30 if not token:
31 print("Error: you are not authenticated. Please run the 'login' command first.")
32 return
33
34 print(f"Loading profile using token: [yellow]{token}[/yellow]")
35
36
37@router.command("logout")
38def logout_handler(response: Response, data_bridge: FromDishka[DataBridge]):
39 try:
40 data_bridge.delete_by_key("auth_token")
41 print("Logout successful. Session data cleared.")
42 except KeyError:
43 print("You were not authenticated anyway.")
How it works:
When calling a handler,
dishkaautomatically injects aDataBridgeinstance.The
login --username <name>command callslogin_handler, which saves the token through the injecteddata_bridge.The
get-profilecommand callsget_profile_handler, which also receivesdata_bridgeand extracts the token from it.
- class DataBridge¶
- __init__(self, initial_data: dict | None = None)
Initializes the storage. When used through DI, it is called automatically.
- update(self, data: dict) None¶
Updates the storage with data from a dictionary.
- get_all(self) dict¶
Returns all data from the storage.
- get_by_key(self, key: str) Any¶
Returns the value by key or
Noneif the key is not found.
- delete_by_key(self, key: str) None¶
Deletes the value by key. Raises
KeyErrorif the key is not found.
- clear_all(self) None¶
Completely clears the storage.