Skip to content

prefect.blocks.core

Block

Bases: BaseModel, ABC

A base class for implementing a block that wraps an external service.

This class can be defined with an arbitrary set of fields and methods, and couples business logic with data contained in an block document. _block_document_name, _block_document_id, _block_schema_id, and _block_type_id are reserved by Prefect as Block metadata fields, but otherwise a Block can implement arbitrary logic. Blocks can be instantiated without populating these metadata fields, but can only be used interactively, not with the Prefect API.

Instead of the init method, a block implementation allows the definition of a block_initialization method that is called after initialization.

Source code in src/prefect/blocks/core.py
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
@register_base_type
class Block(BaseModel, ABC):
    """
    A base class for implementing a block that wraps an external service.

    This class can be defined with an arbitrary set of fields and methods, and
    couples business logic with data contained in an block document.
    `_block_document_name`, `_block_document_id`, `_block_schema_id`, and
    `_block_type_id` are reserved by Prefect as Block metadata fields, but
    otherwise a Block can implement arbitrary logic. Blocks can be instantiated
    without populating these metadata fields, but can only be used interactively,
    not with the Prefect API.

    Instead of the __init__ method, a block implementation allows the
    definition of a `block_initialization` method that is called after
    initialization.
    """

    model_config = ConfigDict(
        extra="allow",
        json_schema_extra=schema_extra,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.block_initialization()

    def __str__(self) -> str:
        return self.__repr__()

    def __repr_args__(self):
        repr_args = super().__repr_args__()
        data_keys = self.model_json_schema()["properties"].keys()
        return [
            (key, value) for key, value in repr_args if key is None or key in data_keys
        ]

    def block_initialization(self) -> None:
        pass

    # -- private class variables
    # set by the class itself

    # Attribute to customize the name of the block type created
    # when the block is registered with the API. If not set, block
    # type name will default to the class name.
    _block_type_name: ClassVar[Optional[str]] = None
    _block_type_slug: ClassVar[Optional[str]] = None

    # Attributes used to set properties on a block type when registered
    # with the API.
    _logo_url: ClassVar[Optional[HttpUrl]] = None
    _documentation_url: ClassVar[Optional[HttpUrl]] = None
    _description: ClassVar[Optional[str]] = None
    _code_example: ClassVar[Optional[str]] = None
    _block_type_id: ClassVar[Optional[UUID]] = None
    _block_schema_id: ClassVar[Optional[UUID]] = None
    _block_schema_capabilities: ClassVar[Optional[List[str]]] = None
    _block_schema_version: ClassVar[Optional[str]] = None

    # -- private instance variables
    # these are set when blocks are loaded from the API

    _block_document_id: Optional[UUID] = PrivateAttr(None)
    _block_document_name: Optional[str] = PrivateAttr(None)
    _is_anonymous: Optional[bool] = PrivateAttr(None)

    # Exclude `save` as it uses the `sync_compatible` decorator and needs to be
    # decorated directly.
    _events_excluded_methods = ["block_initialization", "save", "dict"]

    @classmethod
    def __dispatch_key__(cls):
        if cls.__name__ == "Block":
            return None  # The base class is abstract
        return block_schema_to_key(cls._to_block_schema())

    @model_serializer(mode="wrap")
    def ser_model(self, handler: Callable, info: SerializationInfo) -> Any:
        jsonable_self = handler(self)
        if (ctx := info.context) and ctx.get("include_secrets") is True:
            jsonable_self.update(
                {
                    field_name: visit_collection(
                        expr=getattr(self, field_name),
                        visit_fn=partial(handle_secret_render, context=ctx),
                        return_data=True,
                    )
                    for field_name in self.model_fields
                }
            )
        if extra_fields := {
            "block_type_slug": self.get_block_type_slug(),
            "_block_document_id": self._block_document_id,
            "_block_document_name": self._block_document_name,
            "_is_anonymous": self._is_anonymous,
        }:
            jsonable_self |= {
                key: value for key, value in extra_fields.items() if value is not None
            }
        return jsonable_self

    @classmethod
    def get_block_type_name(cls):
        return cls._block_type_name or cls.__name__

    @classmethod
    def get_block_type_slug(cls):
        return slugify(cls._block_type_slug or cls.get_block_type_name())

    @classmethod
    def get_block_capabilities(cls) -> FrozenSet[str]:
        """
        Returns the block capabilities for this Block. Recursively collects all block
        capabilities of all parent classes into a single frozenset.
        """
        return frozenset(
            {
                c
                for base in (cls,) + cls.__mro__
                for c in getattr(base, "_block_schema_capabilities", []) or []
            }
        )

    @classmethod
    def _get_current_package_version(cls):
        current_module = inspect.getmodule(cls)
        if current_module:
            top_level_module = sys.modules[
                current_module.__name__.split(".")[0] or "__main__"
            ]
            try:
                version = Version(top_level_module.__version__)
                # Strips off any local version information
                return version.base_version
            except (AttributeError, InvalidVersion):
                # Module does not have a __version__ attribute or is not a parsable format
                pass
        return DEFAULT_BLOCK_SCHEMA_VERSION

    @classmethod
    def get_block_schema_version(cls) -> str:
        return cls._block_schema_version or cls._get_current_package_version()

    @classmethod
    def _to_block_schema_reference_dict(cls):
        return dict(
            block_type_slug=cls.get_block_type_slug(),
            block_schema_checksum=cls._calculate_schema_checksum(),
        )

    @classmethod
    def _calculate_schema_checksum(
        cls, block_schema_fields: Optional[Dict[str, Any]] = None
    ):
        """
        Generates a unique hash for the underlying schema of block.

        Args:
            block_schema_fields: Dictionary detailing block schema fields to generate a
                checksum for. The fields of the current class is used if this parameter
                is not provided.

        Returns:
            str: The calculated checksum prefixed with the hashing algorithm used.
        """
        block_schema_fields = (
            cls.model_json_schema()
            if block_schema_fields is None
            else block_schema_fields
        )
        fields_for_checksum = remove_nested_keys(["secret_fields"], block_schema_fields)
        if fields_for_checksum.get("definitions"):
            non_block_definitions = _get_non_block_reference_definitions(
                fields_for_checksum, fields_for_checksum["definitions"]
            )
            if non_block_definitions:
                fields_for_checksum["definitions"] = non_block_definitions
            else:
                # Pop off definitions entirely instead of empty dict for consistency
                # with the OpenAPI specification
                fields_for_checksum.pop("definitions")
        checksum = hash_objects(fields_for_checksum, hash_algo=hashlib.sha256)
        if checksum is None:
            raise ValueError("Unable to compute checksum for block schema")
        else:
            return f"sha256:{checksum}"

    def _to_block_document(
        self,
        name: Optional[str] = None,
        block_schema_id: Optional[UUID] = None,
        block_type_id: Optional[UUID] = None,
        is_anonymous: Optional[bool] = None,
        include_secrets: bool = False,
    ) -> BlockDocument:
        """
        Creates the corresponding block document based on the data stored in a block.
        The corresponding block document name, block type ID, and block schema ID must
        either be passed into the method or configured on the block.

        Args:
            name: The name of the created block document. Not required if anonymous.
            block_schema_id: UUID of the corresponding block schema.
            block_type_id: UUID of the corresponding block type.
            is_anonymous: if True, an anonymous block is created. Anonymous
                blocks are not displayed in the UI and used primarily for system
                operations and features that need to automatically generate blocks.

        Returns:
            BlockDocument: Corresponding block document
                populated with the block's configured data.
        """
        if is_anonymous is None:
            is_anonymous = self._is_anonymous or False

        # name must be present if not anonymous
        if not is_anonymous and not name and not self._block_document_name:
            raise ValueError("No name provided, either as an argument or on the block.")

        if not block_schema_id and not self._block_schema_id:
            raise ValueError(
                "No block schema ID provided, either as an argument or on the block."
            )
        if not block_type_id and not self._block_type_id:
            raise ValueError(
                "No block type ID provided, either as an argument or on the block."
            )

        # The keys passed to `include` must NOT be aliases, else some items will be missed
        # i.e. must do `self.schema_` vs `self.schema` to get a `schema_ = Field(alias="schema")`
        # reported from https://github.com/PrefectHQ/prefect-dbt/issues/54
        data_keys = self.model_json_schema(by_alias=False)["properties"].keys()

        # `block_document_data`` must return the aliased version for it to show in the UI
        block_document_data = self.model_dump(
            by_alias=True,
            include=data_keys,
            context={"include_secrets": include_secrets},
        )

        # Iterate through and find blocks that already have saved block documents to
        # create references to those saved block documents.
        for key in data_keys:
            field_value = getattr(self, key)
            if (
                isinstance(field_value, Block)
                and field_value._block_document_id is not None
            ):
                block_document_data[key] = {
                    "$ref": {"block_document_id": field_value._block_document_id}
                }

        return BlockDocument(
            id=self._block_document_id or uuid4(),
            name=(name or self._block_document_name) if not is_anonymous else None,
            block_schema_id=block_schema_id or self._block_schema_id,
            block_type_id=block_type_id or self._block_type_id,
            data=block_document_data,
            block_schema=self._to_block_schema(
                block_type_id=block_type_id or self._block_type_id,
            ),
            block_type=self._to_block_type(),
            is_anonymous=is_anonymous,
        )

    @classmethod
    def _to_block_schema(cls, block_type_id: Optional[UUID] = None) -> BlockSchema:
        """
        Creates the corresponding block schema of the block.
        The corresponding block_type_id must either be passed into
        the method or configured on the block.

        Args:
            block_type_id: UUID of the corresponding block type.

        Returns:
            BlockSchema: The corresponding block schema.
        """
        fields = cls.model_json_schema()
        return BlockSchema(
            id=cls._block_schema_id if cls._block_schema_id is not None else uuid4(),
            checksum=cls._calculate_schema_checksum(),
            fields=fields,
            block_type_id=block_type_id or cls._block_type_id,
            block_type=cls._to_block_type(),
            capabilities=list(cls.get_block_capabilities()),
            version=cls.get_block_schema_version(),
        )

    @classmethod
    def _parse_docstring(cls) -> List[DocstringSection]:
        """
        Parses the docstring into list of DocstringSection objects.
        Helper method used primarily to suppress irrelevant logs, e.g.
        `<module>:11: No type or annotation for parameter 'write_json'`
        because griffe is unable to parse the types from pydantic.BaseModel.
        """
        with disable_logger("griffe"):
            docstring = Docstring(cls.__doc__)
            parsed = parse(docstring, Parser.google)
        return parsed

    @classmethod
    def get_description(cls) -> Optional[str]:
        """
        Returns the description for the current block. Attempts to parse
        description from class docstring if an override is not defined.
        """
        description = cls._description
        # If no description override has been provided, find the first text section
        # and use that as the description
        if description is None and cls.__doc__ is not None:
            parsed = cls._parse_docstring()
            parsed_description = next(
                (
                    section.as_dict().get("value")
                    for section in parsed
                    if section.kind == DocstringSectionKind.text
                ),
                None,
            )
            if isinstance(parsed_description, str):
                description = parsed_description.strip()
        return description

    @classmethod
    def get_code_example(cls) -> Optional[str]:
        """
        Returns the code example for the given block. Attempts to parse
        code example from the class docstring if an override is not provided.
        """
        code_example = (
            dedent(text=cls._code_example) if cls._code_example is not None else None
        )
        # If no code example override has been provided, attempt to find a examples
        # section or an admonition with the annotation "example" and use that as the
        # code example
        if code_example is None and cls.__doc__ is not None:
            parsed = cls._parse_docstring()
            for section in parsed:
                # Section kind will be "examples" if Examples section heading is used.
                if section.kind == DocstringSectionKind.examples:
                    # Examples sections are made up of smaller sections that need to be
                    # joined with newlines. Smaller sections are represented as tuples
                    # with shape (DocstringSectionKind, str)
                    code_example = "\n".join(
                        (part[1] for part in section.as_dict().get("value", []))
                    )
                    break
                # Section kind will be "admonition" if Example section heading is used.
                if section.kind == DocstringSectionKind.admonition:
                    value = section.as_dict().get("value", {})
                    if value.get("annotation") == "example":
                        code_example = value.get("description")
                        break

        if code_example is None:
            # If no code example has been specified or extracted from the class
            # docstring, generate a sensible default
            code_example = cls._generate_code_example()

        return code_example

    @classmethod
    def _generate_code_example(cls) -> str:
        """Generates a default code example for the current class"""
        qualified_name = to_qualified_name(cls)
        module_str = ".".join(qualified_name.split(".")[:-1])
        class_name = cls.__name__
        block_variable_name = f'{cls.get_block_type_slug().replace("-", "_")}_block'

        return dedent(
            f"""\
        ```python
        from {module_str} import {class_name}

        {block_variable_name} = {class_name}.load("BLOCK_NAME")
        ```"""
        )

    @classmethod
    def _to_block_type(cls) -> BlockType:
        """
        Creates the corresponding block type of the block.

        Returns:
            BlockType: The corresponding block type.
        """
        return BlockType(
            id=cls._block_type_id or uuid4(),
            slug=cls.get_block_type_slug(),
            name=cls.get_block_type_name(),
            logo_url=cls._logo_url,
            documentation_url=cls._documentation_url,
            description=cls.get_description(),
            code_example=cls.get_code_example(),
        )

    @classmethod
    def _from_block_document(cls, block_document: BlockDocument) -> Self:
        """
        Instantiates a block from a given block document. The corresponding block class
        will be looked up in the block registry based on the corresponding block schema
        of the provided block document.

        Args:
            block_document: The block document used to instantiate a block.

        Raises:
            ValueError: If the provided block document doesn't have a corresponding block
                schema.

        Returns:
            Block: Hydrated block with data from block document.
        """
        if block_document.block_schema is None:
            raise ValueError(
                "Unable to determine block schema for provided block document"
            )

        block_cls = (
            cls
            if cls.__name__ != "Block"
            # Look up the block class by dispatch
            else cls.get_block_class_from_schema(block_document.block_schema)
        )

        block = block_cls.model_validate(block_document.data)
        block._block_document_id = block_document.id
        block.__class__._block_schema_id = block_document.block_schema_id
        block.__class__._block_type_id = block_document.block_type_id
        block._block_document_name = block_document.name
        block._is_anonymous = block_document.is_anonymous
        block._define_metadata_on_nested_blocks(
            block_document.block_document_references
        )

        resources: Optional[ResourceTuple] = block._event_method_called_resources()
        if resources:
            kind = block._event_kind()
            resource, related = resources
            emit_event(event=f"{kind}.loaded", resource=resource, related=related)

        return block

    def _event_kind(self) -> str:
        return f"prefect.block.{self.get_block_type_slug()}"

    def _event_method_called_resources(self) -> Optional[ResourceTuple]:
        if not (self._block_document_id and self._block_document_name):
            return None

        return (
            {
                "prefect.resource.id": (
                    f"prefect.block-document.{self._block_document_id}"
                ),
                "prefect.resource.name": self._block_document_name,
            },
            [
                {
                    "prefect.resource.id": (
                        f"prefect.block-type.{self.get_block_type_slug()}"
                    ),
                    "prefect.resource.role": "block-type",
                }
            ],
        )

    @classmethod
    def get_block_class_from_schema(cls: Type[Self], schema: BlockSchema) -> Type[Self]:
        """
        Retrieve the block class implementation given a schema.
        """
        return cls.get_block_class_from_key(block_schema_to_key(schema))

    @classmethod
    def get_block_class_from_key(cls: Type[Self], key: str) -> Type[Self]:
        """
        Retrieve the block class implementation given a key.
        """

        # Ensure collections are imported and have the opportunity to register types
        # before looking up the block class, but only do this once
        load_prefect_collections()

        return lookup_type(cls, key)

    def _define_metadata_on_nested_blocks(
        self, block_document_references: Dict[str, Dict[str, Any]]
    ):
        """
        Recursively populates metadata fields on nested blocks based on the
        provided block document references.
        """
        for item in block_document_references.items():
            field_name, block_document_reference = item
            nested_block = getattr(self, field_name)
            if isinstance(nested_block, Block):
                nested_block_document_info = block_document_reference.get(
                    "block_document", {}
                )
                nested_block._define_metadata_on_nested_blocks(
                    nested_block_document_info.get("block_document_references", {})
                )
                nested_block_document_id = nested_block_document_info.get("id")
                nested_block._block_document_id = (
                    UUID(nested_block_document_id) if nested_block_document_id else None
                )
                nested_block._block_document_name = nested_block_document_info.get(
                    "name"
                )
                nested_block._is_anonymous = nested_block_document_info.get(
                    "is_anonymous"
                )

    @classmethod
    @inject_client
    async def _get_block_document(
        cls,
        name: str,
        client: Optional["PrefectClient"] = None,
    ):
        if cls.__name__ == "Block":
            block_type_slug, block_document_name = name.split("/", 1)
        else:
            block_type_slug = cls.get_block_type_slug()
            block_document_name = name

        try:
            block_document = await client.read_block_document_by_name(
                name=block_document_name, block_type_slug=block_type_slug
            )
        except prefect.exceptions.ObjectNotFound as e:
            raise ValueError(
                f"Unable to find block document named {block_document_name} for block"
                f" type {block_type_slug}"
            ) from e

        return block_document, block_document_name

    @classmethod
    @sync_compatible
    @inject_client
    async def _get_block_document_by_id(
        cls,
        block_document_id: Union[str, uuid.UUID],
        client: Optional["PrefectClient"] = None,
    ):
        if isinstance(block_document_id, str):
            try:
                block_document_id = UUID(block_document_id)
            except ValueError:
                raise ValueError(
                    f"Block document ID {block_document_id!r} is not a valid UUID"
                )

        try:
            block_document = await client.read_block_document(
                block_document_id=block_document_id
            )
        except prefect.exceptions.ObjectNotFound:
            raise ValueError(
                f"Unable to find block document with ID {block_document_id!r}"
            )

        return block_document, block_document.name

    @classmethod
    @sync_compatible
    @inject_client
    async def load(
        cls,
        name: str,
        validate: bool = True,
        client: Optional["PrefectClient"] = None,
    ) -> "Self":
        """
        Retrieves data from the block document with the given name for the block type
        that corresponds with the current class and returns an instantiated version of
        the current class with the data stored in the block document.

        If a block document for a given block type is saved with a different schema
        than the current class calling `load`, a warning will be raised.

        If the current class schema is a subset of the block document schema, the block
        can be loaded as normal using the default `validate = True`.

        If the current class schema is a superset of the block document schema, `load`
        must be called with `validate` set to False to prevent a validation error. In
        this case, the block attributes will default to `None` and must be set manually
        and saved to a new block document before the block can be used as expected.

        Args:
            name: The name or slug of the block document. A block document slug is a
                string with the format <block_type_slug>/<block_document_name>
            validate: If False, the block document will be loaded without Pydantic
                validating the block schema. This is useful if the block schema has
                changed client-side since the block document referred to by `name` was saved.
            client: The client to use to load the block document. If not provided, the
                default client will be injected.

        Raises:
            ValueError: If the requested block document is not found.

        Returns:
            An instance of the current class hydrated with the data stored in the
            block document with the specified name.

        Examples:
            Load from a Block subclass with a block document name:
            ```python
            class Custom(Block):
                message: str

            Custom(message="Hello!").save("my-custom-message")

            loaded_block = Custom.load("my-custom-message")
            ```

            Load from Block with a block document slug:
            ```python
            class Custom(Block):
                message: str

            Custom(message="Hello!").save("my-custom-message")

            loaded_block = Block.load("custom/my-custom-message")
            ```

            Migrate a block document to a new schema:
            ```python
            # original class
            class Custom(Block):
                message: str

            Custom(message="Hello!").save("my-custom-message")

            # Updated class with new required field
            class Custom(Block):
                message: str
                number_of_ducks: int

            loaded_block = Custom.load("my-custom-message", validate=False)

            # Prints UserWarning about schema mismatch

            loaded_block.number_of_ducks = 42

            loaded_block.save("my-custom-message", overwrite=True)
            ```
        """
        block_document, block_document_name = await cls._get_block_document(
            name, client=client
        )

        return cls._load_from_block_document(block_document, validate=validate)

    @classmethod
    @sync_compatible
    @inject_client
    async def load_from_ref(
        cls,
        ref: Union[str, UUID, Dict[str, Any]],
        validate: bool = True,
        client: Optional["PrefectClient"] = None,
    ) -> "Self":
        """
        Retrieves data from the block document by given reference for the block type
        that corresponds with the current class and returns an instantiated version of
        the current class with the data stored in the block document.

        Provided reference can be a block document ID, or a reference data in dictionary format.
        Supported dictionary reference formats are:
        - {"block_document_id": <block_document_id>}
        - {"block_document_slug": <block_document_slug>}

        If a block document for a given block type is saved with a different schema
        than the current class calling `load`, a warning will be raised.

        If the current class schema is a subset of the block document schema, the block
        can be loaded as normal using the default `validate = True`.

        If the current class schema is a superset of the block document schema, `load`
        must be called with `validate` set to False to prevent a validation error. In
        this case, the block attributes will default to `None` and must be set manually
        and saved to a new block document before the block can be used as expected.

        Args:
            ref: The reference to the block document. This can be a block document ID,
                or one of supported dictionary reference formats.
            validate: If False, the block document will be loaded without Pydantic
                validating the block schema. This is useful if the block schema has
                changed client-side since the block document referred to by `name` was saved.
            client: The client to use to load the block document. If not provided, the
                default client will be injected.

        Raises:
            ValueError: If invalid reference format is provided.
            ValueError: If the requested block document is not found.

        Returns:
            An instance of the current class hydrated with the data stored in the
            block document with the specified name.

        """
        block_document = None
        if isinstance(ref, (str, UUID)):
            block_document, _ = await cls._get_block_document_by_id(ref)
        elif isinstance(ref, dict):
            if block_document_id := ref.get("block_document_id"):
                block_document, _ = await cls._get_block_document_by_id(
                    block_document_id
                )
            elif block_document_slug := ref.get("block_document_slug"):
                block_document, _ = await cls._get_block_document(block_document_slug)

        if not block_document:
            raise ValueError(f"Invalid reference format {ref!r}.")

        return cls._load_from_block_document(block_document, validate=validate)

    @classmethod
    def _load_from_block_document(
        cls, block_document: BlockDocument, validate: bool = True
    ) -> "Self":
        """
        Loads a block from a given block document.

        If a block document for a given block type is saved with a different schema
        than the current class calling `load`, a warning will be raised.

        If the current class schema is a subset of the block document schema, the block
        can be loaded as normal using the default `validate = True`.

        If the current class schema is a superset of the block document schema, `load`
        must be called with `validate` set to False to prevent a validation error. In
        this case, the block attributes will default to `None` and must be set manually
        and saved to a new block document before the block can be used as expected.

        Args:
            block_document: The block document used to instantiate a block.
            validate: If False, the block document will be loaded without Pydantic
                validating the block schema. This is useful if the block schema has
                changed client-side since the block document referred to by `name` was saved.

        Raises:
            ValueError: If the requested block document is not found.

        Returns:
            An instance of the current class hydrated with the data stored in the
            block document with the specified name.

        """
        try:
            return cls._from_block_document(block_document)
        except ValidationError as e:
            if not validate:
                missing_fields = tuple(err["loc"][0] for err in e.errors())
                missing_block_data = {field: None for field in missing_fields}
                warnings.warn(
                    f"Could not fully load {block_document.name!r} of block type"
                    f" {cls.get_block_type_slug()!r} - this is likely because one or more"
                    " required fields were added to the schema for"
                    f" {cls.__name__!r} that did not exist on the class when this block"
                    " was last saved. Please specify values for new field(s):"
                    f" {listrepr(missing_fields)}, then run"
                    f' `{cls.__name__}.save("{block_document.name}", overwrite=True)`,'
                    " and load this block again before attempting to use it."
                )
                return cls.model_construct(**block_document.data, **missing_block_data)
            raise RuntimeError(
                f"Unable to load {block_document.name!r} of block type"
                f" {cls.get_block_type_slug()!r} due to failed validation. To load without"
                " validation, try loading again with `validate=False`."
            ) from e

    @staticmethod
    def is_block_class(block) -> bool:
        return _is_subclass(block, Block)

    @staticmethod
    def annotation_refers_to_block_class(annotation: Any) -> bool:
        if Block.is_block_class(annotation):
            return True

        if get_origin(annotation) is Union:
            for annotation in get_args(annotation):
                if Block.is_block_class(annotation):
                    return True

        return False

    @classmethod
    @sync_compatible
    @inject_client
    async def register_type_and_schema(cls, client: Optional["PrefectClient"] = None):
        """
        Makes block available for configuration with current Prefect API.
        Recursively registers all nested blocks. Registration is idempotent.

        Args:
            client: Optional client to use for registering type and schema with the
                Prefect API. A new client will be created and used if one is not
                provided.
        """
        if cls.__name__ == "Block":
            raise InvalidBlockRegistration(
                "`register_type_and_schema` should be called on a Block "
                "subclass and not on the Block class directly."
            )
        if ABC in getattr(cls, "__bases__", []):
            raise InvalidBlockRegistration(
                "`register_type_and_schema` should be called on a Block "
                "subclass and not on a Block interface class directly."
            )

        async def register_blocks_in_annotation(annotation: type) -> None:
            """Walk through the annotation and register any nested blocks."""
            if Block.is_block_class(annotation):
                await annotation.register_type_and_schema(client=client)
            elif get_origin(annotation) in (Union, tuple, list, dict):
                for inner_annotation in get_args(annotation):
                    await register_blocks_in_annotation(inner_annotation)

        for field in cls.model_fields.values():
            await register_blocks_in_annotation(field.annotation)

        try:
            block_type = await client.read_block_type_by_slug(
                slug=cls.get_block_type_slug()
            )

            cls._block_type_id = block_type.id

            local_block_type = cls._to_block_type()
            if _should_update_block_type(
                local_block_type=local_block_type, server_block_type=block_type
            ):
                await client.update_block_type(
                    block_type_id=block_type.id, block_type=local_block_type
                )
        except prefect.exceptions.ObjectNotFound:
            block_type = await client.create_block_type(block_type=cls._to_block_type())
            cls._block_type_id = block_type.id

        try:
            block_schema = await client.read_block_schema_by_checksum(
                checksum=cls._calculate_schema_checksum(),
                version=cls.get_block_schema_version(),
            )
        except prefect.exceptions.ObjectNotFound:
            block_schema = await client.create_block_schema(
                block_schema=cls._to_block_schema(block_type_id=block_type.id)
            )

        cls._block_schema_id = block_schema.id

    @inject_client
    async def _save(
        self,
        name: Optional[str] = None,
        is_anonymous: bool = False,
        overwrite: bool = False,
        client: Optional["PrefectClient"] = None,
    ):
        """
        Saves the values of a block as a block document with an option to save as an
        anonymous block document.

        Args:
            name: User specified name to give saved block document which can later be used to load the
                block document.
            is_anonymous: Boolean value specifying whether the block document is anonymous. Anonymous
                blocks are intended for system use and are not shown in the UI. Anonymous blocks do not
                require a user-supplied name.
            overwrite: Boolean value specifying if values should be overwritten if a block document with
                the specified name already exists.

        Raises:
            ValueError: If a name is not given and `is_anonymous` is `False` or a name is given and
                `is_anonymous` is `True`.
        """
        if name is None and not is_anonymous:
            if self._block_document_name is None:
                raise ValueError(
                    "You're attempting to save a block document without a name."
                    " Please either call `save` with a `name` or pass"
                    " `is_anonymous=True` to save an anonymous block."
                )
            else:
                name = self._block_document_name

        self._is_anonymous = is_anonymous

        # Ensure block type and schema are registered before saving block document.
        await self.register_type_and_schema(client=client)

        try:
            block_document = await client.create_block_document(
                block_document=self._to_block_document(name=name)
            )
        except prefect.exceptions.ObjectAlreadyExists as err:
            if overwrite:
                block_document_id = self._block_document_id
                if block_document_id is None:
                    existing_block_document = await client.read_block_document_by_name(
                        name=name, block_type_slug=self.get_block_type_slug()
                    )
                    block_document_id = existing_block_document.id
                await client.update_block_document(
                    block_document_id=block_document_id,
                    block_document=self._to_block_document(
                        name=name, include_secrets=True
                    ),
                )
                block_document = await client.read_block_document(
                    block_document_id=block_document_id
                )
            else:
                raise ValueError(
                    "You are attempting to save values with a name that is already in"
                    " use for this block type. If you would like to overwrite the"
                    " values that are saved, then save with `overwrite=True`."
                ) from err

        # Update metadata on block instance for later use.
        self._block_document_name = block_document.name
        self._block_document_id = block_document.id
        return self._block_document_id

    @sync_compatible
    async def save(
        self,
        name: Optional[str] = None,
        overwrite: bool = False,
        client: Optional["PrefectClient"] = None,
    ):
        """
        Saves the values of a block as a block document.

        Args:
            name: User specified name to give saved block document which can later be used to load the
                block document.
            overwrite: Boolean value specifying if values should be overwritten if a block document with
                the specified name already exists.

        """
        document_id = await self._save(name=name, overwrite=overwrite, client=client)

        return document_id

    @classmethod
    @sync_compatible
    @inject_client
    async def delete(
        cls,
        name: str,
        client: Optional["PrefectClient"] = None,
    ):
        block_document, block_document_name = await cls._get_block_document(name)

        await client.delete_block_document(block_document.id)

    def __new__(cls: Type[Self], **kwargs) -> Self:
        """
        Create an instance of the Block subclass type if a `block_type_slug` is
        present in the data payload.
        """
        block_type_slug = kwargs.pop("block_type_slug", None)
        if block_type_slug:
            subcls = lookup_type(cls, dispatch_key=block_type_slug)
            return super().__new__(subcls)
        else:
            return super().__new__(cls)

    def get_block_placeholder(self) -> str:
        """
        Returns the block placeholder for the current block which can be used for
        templating.

        Returns:
            str: The block placeholder for the current block in the format
                `prefect.blocks.{block_type_name}.{block_document_name}`

        Raises:
            BlockNotSavedError: Raised if the block has not been saved.

        If a block has not been saved, the return value will be `None`.
        """
        block_document_name = self._block_document_name
        if not block_document_name:
            raise BlockNotSavedError(
                "Could not generate block placeholder for unsaved block."
            )

        return f"prefect.blocks.{self.get_block_type_slug()}.{block_document_name}"

    @classmethod
    def model_json_schema(
        cls,
        by_alias: bool = True,
        ref_template: str = "#/definitions/{model}",
        schema_generator: Type[GenerateJsonSchema] = GenerateJsonSchema,
        mode: Literal["validation", "serialization"] = "validation",
    ) -> Dict[str, Any]:
        """TODO: stop overriding this method - use GenerateSchema in ConfigDict instead?"""
        schema = super().model_json_schema(
            by_alias, ref_template, schema_generator, mode
        )

        # ensure backwards compatibility by copying $defs into definitions
        if "$defs" in schema:
            schema["definitions"] = schema.pop("$defs")

        # we aren't expecting these additional fields in the schema
        if "additionalProperties" in schema:
            schema.pop("additionalProperties")

        for _, definition in schema.get("definitions", {}).items():
            if "additionalProperties" in definition:
                definition.pop("additionalProperties")

        return schema

    @classmethod
    def model_validate(
        cls: type[Self],
        obj: Any,
        *,
        strict: Optional[bool] = None,
        from_attributes: Optional[bool] = None,
        context: Optional[Dict[str, Any]] = None,
    ) -> Self:
        if isinstance(obj, dict):
            extra_serializer_fields = {
                "_block_document_id",
                "_block_document_name",
                "_is_anonymous",
            }.intersection(obj.keys())
            for field in extra_serializer_fields:
                obj.pop(field, None)

        return super().model_validate(
            obj, strict=strict, from_attributes=from_attributes, context=context
        )

    def model_dump(
        self,
        *,
        mode: Union[Literal["json", "python"], str] = "python",
        include: "IncEx" = None,
        exclude: "IncEx" = None,
        context: Optional[Dict[str, Any]] = None,
        by_alias: bool = False,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        round_trip: bool = False,
        warnings: Union[bool, Literal["none", "warn", "error"]] = True,
        serialize_as_any: bool = False,
    ) -> Dict[str, Any]:
        d = super().model_dump(
            mode=mode,
            include=include,
            exclude=exclude,
            context=context,
            by_alias=by_alias,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=exclude_none,
            round_trip=round_trip,
            warnings=warnings,
            serialize_as_any=serialize_as_any,
        )

        extra_serializer_fields = {
            "block_type_slug",
            "_block_document_id",
            "_block_document_name",
            "_is_anonymous",
        }.intersection(d.keys())

        for field in extra_serializer_fields:
            if (include and field not in include) or (exclude and field in exclude):
                d.pop(field)

        return d

__new__(**kwargs)

Create an instance of the Block subclass type if a block_type_slug is present in the data payload.

Source code in src/prefect/blocks/core.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
def __new__(cls: Type[Self], **kwargs) -> Self:
    """
    Create an instance of the Block subclass type if a `block_type_slug` is
    present in the data payload.
    """
    block_type_slug = kwargs.pop("block_type_slug", None)
    if block_type_slug:
        subcls = lookup_type(cls, dispatch_key=block_type_slug)
        return super().__new__(subcls)
    else:
        return super().__new__(cls)

get_block_capabilities() classmethod

Returns the block capabilities for this Block. Recursively collects all block capabilities of all parent classes into a single frozenset.

Source code in src/prefect/blocks/core.py
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def get_block_capabilities(cls) -> FrozenSet[str]:
    """
    Returns the block capabilities for this Block. Recursively collects all block
    capabilities of all parent classes into a single frozenset.
    """
    return frozenset(
        {
            c
            for base in (cls,) + cls.__mro__
            for c in getattr(base, "_block_schema_capabilities", []) or []
        }
    )

get_block_class_from_key(key) classmethod

Retrieve the block class implementation given a key.

Source code in src/prefect/blocks/core.py
737
738
739
740
741
742
743
744
745
746
747
@classmethod
def get_block_class_from_key(cls: Type[Self], key: str) -> Type[Self]:
    """
    Retrieve the block class implementation given a key.
    """

    # Ensure collections are imported and have the opportunity to register types
    # before looking up the block class, but only do this once
    load_prefect_collections()

    return lookup_type(cls, key)

get_block_class_from_schema(schema) classmethod

Retrieve the block class implementation given a schema.

Source code in src/prefect/blocks/core.py
730
731
732
733
734
735
@classmethod
def get_block_class_from_schema(cls: Type[Self], schema: BlockSchema) -> Type[Self]:
    """
    Retrieve the block class implementation given a schema.
    """
    return cls.get_block_class_from_key(block_schema_to_key(schema))

get_block_placeholder()

Returns the block placeholder for the current block which can be used for templating.

Returns:

Name Type Description
str str

The block placeholder for the current block in the format prefect.blocks.{block_type_name}.{block_document_name}

Raises:

Type Description
BlockNotSavedError

Raised if the block has not been saved.

If a block has not been saved, the return value will be None.

Source code in src/prefect/blocks/core.py
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def get_block_placeholder(self) -> str:
    """
    Returns the block placeholder for the current block which can be used for
    templating.

    Returns:
        str: The block placeholder for the current block in the format
            `prefect.blocks.{block_type_name}.{block_document_name}`

    Raises:
        BlockNotSavedError: Raised if the block has not been saved.

    If a block has not been saved, the return value will be `None`.
    """
    block_document_name = self._block_document_name
    if not block_document_name:
        raise BlockNotSavedError(
            "Could not generate block placeholder for unsaved block."
        )

    return f"prefect.blocks.{self.get_block_type_slug()}.{block_document_name}"

get_code_example() classmethod

Returns the code example for the given block. Attempts to parse code example from the class docstring if an override is not provided.

Source code in src/prefect/blocks/core.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
@classmethod
def get_code_example(cls) -> Optional[str]:
    """
    Returns the code example for the given block. Attempts to parse
    code example from the class docstring if an override is not provided.
    """
    code_example = (
        dedent(text=cls._code_example) if cls._code_example is not None else None
    )
    # If no code example override has been provided, attempt to find a examples
    # section or an admonition with the annotation "example" and use that as the
    # code example
    if code_example is None and cls.__doc__ is not None:
        parsed = cls._parse_docstring()
        for section in parsed:
            # Section kind will be "examples" if Examples section heading is used.
            if section.kind == DocstringSectionKind.examples:
                # Examples sections are made up of smaller sections that need to be
                # joined with newlines. Smaller sections are represented as tuples
                # with shape (DocstringSectionKind, str)
                code_example = "\n".join(
                    (part[1] for part in section.as_dict().get("value", []))
                )
                break
            # Section kind will be "admonition" if Example section heading is used.
            if section.kind == DocstringSectionKind.admonition:
                value = section.as_dict().get("value", {})
                if value.get("annotation") == "example":
                    code_example = value.get("description")
                    break

    if code_example is None:
        # If no code example has been specified or extracted from the class
        # docstring, generate a sensible default
        code_example = cls._generate_code_example()

    return code_example

get_description() classmethod

Returns the description for the current block. Attempts to parse description from class docstring if an override is not defined.

Source code in src/prefect/blocks/core.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@classmethod
def get_description(cls) -> Optional[str]:
    """
    Returns the description for the current block. Attempts to parse
    description from class docstring if an override is not defined.
    """
    description = cls._description
    # If no description override has been provided, find the first text section
    # and use that as the description
    if description is None and cls.__doc__ is not None:
        parsed = cls._parse_docstring()
        parsed_description = next(
            (
                section.as_dict().get("value")
                for section in parsed
                if section.kind == DocstringSectionKind.text
            ),
            None,
        )
        if isinstance(parsed_description, str):
            description = parsed_description.strip()
    return description

load(name, validate=True, client=None) async classmethod

Retrieves data from the block document with the given name for the block type that corresponds with the current class and returns an instantiated version of the current class with the data stored in the block document.

If a block document for a given block type is saved with a different schema than the current class calling load, a warning will be raised.

If the current class schema is a subset of the block document schema, the block can be loaded as normal using the default validate = True.

If the current class schema is a superset of the block document schema, load must be called with validate set to False to prevent a validation error. In this case, the block attributes will default to None and must be set manually and saved to a new block document before the block can be used as expected.

Parameters:

Name Type Description Default
name str

The name or slug of the block document. A block document slug is a string with the format /

required
validate bool

If False, the block document will be loaded without Pydantic validating the block schema. This is useful if the block schema has changed client-side since the block document referred to by name was saved.

True
client Optional[PrefectClient]

The client to use to load the block document. If not provided, the default client will be injected.

None

Raises:

Type Description
ValueError

If the requested block document is not found.

Returns:

Type Description
Self

An instance of the current class hydrated with the data stored in the

Self

block document with the specified name.

Examples:

Load from a Block subclass with a block document name:

class Custom(Block):
    message: str

Custom(message="Hello!").save("my-custom-message")

loaded_block = Custom.load("my-custom-message")

Load from Block with a block document slug:

class Custom(Block):
    message: str

Custom(message="Hello!").save("my-custom-message")

loaded_block = Block.load("custom/my-custom-message")

Migrate a block document to a new schema:

# original class
class Custom(Block):
    message: str

Custom(message="Hello!").save("my-custom-message")

# Updated class with new required field
class Custom(Block):
    message: str
    number_of_ducks: int

loaded_block = Custom.load("my-custom-message", validate=False)

# Prints UserWarning about schema mismatch

loaded_block.number_of_ducks = 42

loaded_block.save("my-custom-message", overwrite=True)
Source code in src/prefect/blocks/core.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
@classmethod
@sync_compatible
@inject_client
async def load(
    cls,
    name: str,
    validate: bool = True,
    client: Optional["PrefectClient"] = None,
) -> "Self":
    """
    Retrieves data from the block document with the given name for the block type
    that corresponds with the current class and returns an instantiated version of
    the current class with the data stored in the block document.

    If a block document for a given block type is saved with a different schema
    than the current class calling `load`, a warning will be raised.

    If the current class schema is a subset of the block document schema, the block
    can be loaded as normal using the default `validate = True`.

    If the current class schema is a superset of the block document schema, `load`
    must be called with `validate` set to False to prevent a validation error. In
    this case, the block attributes will default to `None` and must be set manually
    and saved to a new block document before the block can be used as expected.

    Args:
        name: The name or slug of the block document. A block document slug is a
            string with the format <block_type_slug>/<block_document_name>
        validate: If False, the block document will be loaded without Pydantic
            validating the block schema. This is useful if the block schema has
            changed client-side since the block document referred to by `name` was saved.
        client: The client to use to load the block document. If not provided, the
            default client will be injected.

    Raises:
        ValueError: If the requested block document is not found.

    Returns:
        An instance of the current class hydrated with the data stored in the
        block document with the specified name.

    Examples:
        Load from a Block subclass with a block document name:
        ```python
        class Custom(Block):
            message: str

        Custom(message="Hello!").save("my-custom-message")

        loaded_block = Custom.load("my-custom-message")
        ```

        Load from Block with a block document slug:
        ```python
        class Custom(Block):
            message: str

        Custom(message="Hello!").save("my-custom-message")

        loaded_block = Block.load("custom/my-custom-message")
        ```

        Migrate a block document to a new schema:
        ```python
        # original class
        class Custom(Block):
            message: str

        Custom(message="Hello!").save("my-custom-message")

        # Updated class with new required field
        class Custom(Block):
            message: str
            number_of_ducks: int

        loaded_block = Custom.load("my-custom-message", validate=False)

        # Prints UserWarning about schema mismatch

        loaded_block.number_of_ducks = 42

        loaded_block.save("my-custom-message", overwrite=True)
        ```
    """
    block_document, block_document_name = await cls._get_block_document(
        name, client=client
    )

    return cls._load_from_block_document(block_document, validate=validate)

load_from_ref(ref, validate=True, client=None) async classmethod

Retrieves data from the block document by given reference for the block type that corresponds with the current class and returns an instantiated version of the current class with the data stored in the block document.

Provided reference can be a block document ID, or a reference data in dictionary format. Supported dictionary reference formats are: - {"block_document_id": } - {"block_document_slug": }

If a block document for a given block type is saved with a different schema than the current class calling load, a warning will be raised.

If the current class schema is a subset of the block document schema, the block can be loaded as normal using the default validate = True.

If the current class schema is a superset of the block document schema, load must be called with validate set to False to prevent a validation error. In this case, the block attributes will default to None and must be set manually and saved to a new block document before the block can be used as expected.

Parameters:

Name Type Description Default
ref Union[str, UUID, Dict[str, Any]]

The reference to the block document. This can be a block document ID, or one of supported dictionary reference formats.

required
validate bool

If False, the block document will be loaded without Pydantic validating the block schema. This is useful if the block schema has changed client-side since the block document referred to by name was saved.

True
client Optional[PrefectClient]

The client to use to load the block document. If not provided, the default client will be injected.

None

Raises:

Type Description
ValueError

If invalid reference format is provided.

ValueError

If the requested block document is not found.

Returns:

Type Description
Self

An instance of the current class hydrated with the data stored in the

Self

block document with the specified name.

Source code in src/prefect/blocks/core.py
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
@classmethod
@sync_compatible
@inject_client
async def load_from_ref(
    cls,
    ref: Union[str, UUID, Dict[str, Any]],
    validate: bool = True,
    client: Optional["PrefectClient"] = None,
) -> "Self":
    """
    Retrieves data from the block document by given reference for the block type
    that corresponds with the current class and returns an instantiated version of
    the current class with the data stored in the block document.

    Provided reference can be a block document ID, or a reference data in dictionary format.
    Supported dictionary reference formats are:
    - {"block_document_id": <block_document_id>}
    - {"block_document_slug": <block_document_slug>}

    If a block document for a given block type is saved with a different schema
    than the current class calling `load`, a warning will be raised.

    If the current class schema is a subset of the block document schema, the block
    can be loaded as normal using the default `validate = True`.

    If the current class schema is a superset of the block document schema, `load`
    must be called with `validate` set to False to prevent a validation error. In
    this case, the block attributes will default to `None` and must be set manually
    and saved to a new block document before the block can be used as expected.

    Args:
        ref: The reference to the block document. This can be a block document ID,
            or one of supported dictionary reference formats.
        validate: If False, the block document will be loaded without Pydantic
            validating the block schema. This is useful if the block schema has
            changed client-side since the block document referred to by `name` was saved.
        client: The client to use to load the block document. If not provided, the
            default client will be injected.

    Raises:
        ValueError: If invalid reference format is provided.
        ValueError: If the requested block document is not found.

    Returns:
        An instance of the current class hydrated with the data stored in the
        block document with the specified name.

    """
    block_document = None
    if isinstance(ref, (str, UUID)):
        block_document, _ = await cls._get_block_document_by_id(ref)
    elif isinstance(ref, dict):
        if block_document_id := ref.get("block_document_id"):
            block_document, _ = await cls._get_block_document_by_id(
                block_document_id
            )
        elif block_document_slug := ref.get("block_document_slug"):
            block_document, _ = await cls._get_block_document(block_document_slug)

    if not block_document:
        raise ValueError(f"Invalid reference format {ref!r}.")

    return cls._load_from_block_document(block_document, validate=validate)

model_json_schema(by_alias=True, ref_template='#/definitions/{model}', schema_generator=GenerateJsonSchema, mode='validation') classmethod

Source code in src/prefect/blocks/core.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = "#/definitions/{model}",
    schema_generator: Type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: Literal["validation", "serialization"] = "validation",
) -> Dict[str, Any]:
    """TODO: stop overriding this method - use GenerateSchema in ConfigDict instead?"""
    schema = super().model_json_schema(
        by_alias, ref_template, schema_generator, mode
    )

    # ensure backwards compatibility by copying $defs into definitions
    if "$defs" in schema:
        schema["definitions"] = schema.pop("$defs")

    # we aren't expecting these additional fields in the schema
    if "additionalProperties" in schema:
        schema.pop("additionalProperties")

    for _, definition in schema.get("definitions", {}).items():
        if "additionalProperties" in definition:
            definition.pop("additionalProperties")

    return schema

register_type_and_schema(client=None) async classmethod

Makes block available for configuration with current Prefect API. Recursively registers all nested blocks. Registration is idempotent.

Parameters:

Name Type Description Default
client Optional[PrefectClient]

Optional client to use for registering type and schema with the Prefect API. A new client will be created and used if one is not provided.

None
Source code in src/prefect/blocks/core.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
@classmethod
@sync_compatible
@inject_client
async def register_type_and_schema(cls, client: Optional["PrefectClient"] = None):
    """
    Makes block available for configuration with current Prefect API.
    Recursively registers all nested blocks. Registration is idempotent.

    Args:
        client: Optional client to use for registering type and schema with the
            Prefect API. A new client will be created and used if one is not
            provided.
    """
    if cls.__name__ == "Block":
        raise InvalidBlockRegistration(
            "`register_type_and_schema` should be called on a Block "
            "subclass and not on the Block class directly."
        )
    if ABC in getattr(cls, "__bases__", []):
        raise InvalidBlockRegistration(
            "`register_type_and_schema` should be called on a Block "
            "subclass and not on a Block interface class directly."
        )

    async def register_blocks_in_annotation(annotation: type) -> None:
        """Walk through the annotation and register any nested blocks."""
        if Block.is_block_class(annotation):
            await annotation.register_type_and_schema(client=client)
        elif get_origin(annotation) in (Union, tuple, list, dict):
            for inner_annotation in get_args(annotation):
                await register_blocks_in_annotation(inner_annotation)

    for field in cls.model_fields.values():
        await register_blocks_in_annotation(field.annotation)

    try:
        block_type = await client.read_block_type_by_slug(
            slug=cls.get_block_type_slug()
        )

        cls._block_type_id = block_type.id

        local_block_type = cls._to_block_type()
        if _should_update_block_type(
            local_block_type=local_block_type, server_block_type=block_type
        ):
            await client.update_block_type(
                block_type_id=block_type.id, block_type=local_block_type
            )
    except prefect.exceptions.ObjectNotFound:
        block_type = await client.create_block_type(block_type=cls._to_block_type())
        cls._block_type_id = block_type.id

    try:
        block_schema = await client.read_block_schema_by_checksum(
            checksum=cls._calculate_schema_checksum(),
            version=cls.get_block_schema_version(),
        )
    except prefect.exceptions.ObjectNotFound:
        block_schema = await client.create_block_schema(
            block_schema=cls._to_block_schema(block_type_id=block_type.id)
        )

    cls._block_schema_id = block_schema.id

save(name=None, overwrite=False, client=None) async

Saves the values of a block as a block document.

Parameters:

Name Type Description Default
name Optional[str]

User specified name to give saved block document which can later be used to load the block document.

None
overwrite bool

Boolean value specifying if values should be overwritten if a block document with the specified name already exists.

False
Source code in src/prefect/blocks/core.py
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
@sync_compatible
async def save(
    self,
    name: Optional[str] = None,
    overwrite: bool = False,
    client: Optional["PrefectClient"] = None,
):
    """
    Saves the values of a block as a block document.

    Args:
        name: User specified name to give saved block document which can later be used to load the
            block document.
        overwrite: Boolean value specifying if values should be overwritten if a block document with
            the specified name already exists.

    """
    document_id = await self._save(name=name, overwrite=overwrite, client=client)

    return document_id

BlockNotSavedError

Bases: RuntimeError

Raised when a given block is not saved and an operation that requires the block to be saved is attempted.

Source code in src/prefect/blocks/core.py
205
206
207
208
209
210
211
class BlockNotSavedError(RuntimeError):
    """
    Raised when a given block is not saved and an operation that requires
    the block to be saved is attempted.
    """

    pass

InvalidBlockRegistration

Bases: Exception

Raised on attempted registration of the base Block class or a Block interface class

Source code in src/prefect/blocks/core.py
82
83
84
85
86
class InvalidBlockRegistration(Exception):
    """
    Raised on attempted registration of the base Block
    class or a Block interface class
    """

block_schema_to_key(schema)

Defines the unique key used to lookup the Block class for a given schema.

Source code in src/prefect/blocks/core.py
75
76
77
78
79
def block_schema_to_key(schema: BlockSchema) -> str:
    """
    Defines the unique key used to lookup the Block class for a given schema.
    """
    return f"{schema.block_type.slug}"

schema_extra(schema, model)

Customizes Pydantic's schema generation feature to add blocks related information.

Source code in src/prefect/blocks/core.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def schema_extra(schema: Dict[str, Any], model: Type["Block"]):
    """
    Customizes Pydantic's schema generation feature to add blocks related information.
    """
    schema["block_type_slug"] = model.get_block_type_slug()
    # Ensures args and code examples aren't included in the schema
    description = model.get_description()
    if description:
        schema["description"] = description
    else:
        # Prevent the description of the base class from being included in the schema
        schema.pop("description", None)

    # create a list of secret field names
    # secret fields include both top-level keys and dot-delimited nested secret keys
    # A wildcard (*) means that all fields under a given key are secret.
    # for example: ["x", "y", "z.*", "child.a"]
    # means the top-level keys "x" and "y", all keys under "z", and the key "a" of a block
    # nested under the "child" key are all secret. There is no limit to nesting.
    secrets = schema["secret_fields"] = []
    for name, field in model.model_fields.items():
        _collect_secret_fields(name, field.annotation, secrets)

    # create block schema references
    refs = schema["block_schema_references"] = {}

    def collect_block_schema_references(field_name: str, annotation: type) -> None:
        """Walk through the annotation and collect block schemas for any nested blocks."""
        if Block.is_block_class(annotation):
            if isinstance(refs.get(field_name), list):
                refs[field_name].append(annotation._to_block_schema_reference_dict())
            elif isinstance(refs.get(field_name), dict):
                refs[field_name] = [
                    refs[field_name],
                    annotation._to_block_schema_reference_dict(),
                ]
            else:
                refs[field_name] = annotation._to_block_schema_reference_dict()
        if get_origin(annotation) in (Union, list, tuple, dict):
            for type_ in get_args(annotation):
                collect_block_schema_references(field_name, type_)

    for name, field in model.model_fields.items():
        collect_block_schema_references(name, field.annotation)