Blocks
A module for lazy loading Prefect Blocks.
The @lazy_load
decorator is centered around a model to attach blocks to. Each block
is defined with two parts: a block name and a block property. The block name is a
string that identifies the block. The block property is a property that loads the block
on first access. The block property should be decorated with the @lazy_load
decorator,
and the block's type should be specified in the property annotations.
Example:
from prefect.blocks.system import Secret
from prefecto.blocks import lazy_load
class Blocks:
"""Class for lazy loading Prefect Blocks."""
# Define the block name variables
password_block: str = "secret-password"
@property
@lazy_load("password_block")
def password(self) -> Secret:
"""The password block."""
blocks = Blocks()
password = blocks.password
print(password)
# Secret(value=SecretStr('**********'))
print(password.get())
# my-secret-password$123
This technique is useful for preventing the blocks from loading until they are actually
needed. This can be important during unit testing, where connections to the Prefect
server may not exist. The alternative would be to call block.load()
directly, which
would load the block every time it is called and could lead to performance issues.
The loader can be integrated with pydantic-settings
to load block names from
environment variables. This can be achieved by setting the block name variables
as class variables with default values set to the environment variables.
Example:
from pydantic_settings import BaseSettings, SettingsConfigDict
from prefect.blocks.system import Secret
from prefecto.blocks import lazy_load
class Blocks(BaseSettings):
"""Class for lazy loading Prefect Blocks."""
model_config = SettingsConfigDict(env_prefix="BLOCKS_")
# Define the block name variables
password_block: str = "secret-password"
@property
@lazy_load("password_block")
def password(self) -> Secret:
"""The password block."""
lazy_load(varname)
Decorator for lazy loading a block.
Parameters: |
|
---|
Returns: |
|
---|
Example:
Specify the block name, then create a decorated property to load the block on first access.
class MyClass:
block_name = "block_name"
@property
@lazy_load("block_name")
def block(self) -> BlockType:
"""The block."""
load_block(block_type, block_name)
async
Load a block.
Parameters: |
|
---|